search
HomeWeb Front-endJS TutorialA simple introductory tutorial for Node.js under Windows system_node.js

With Paypal and Netflix recently announcing their migration to Node.js, the server-side Javascript platform has proven its value in the enterprise field. This is a small step for Node, but a big leap for Javascript. ! Programmers from .NET, Java, PHP, Ruby on Rails and more technical fields, all server-side coders will converge on this platform. As big players like Yahoo, Walmart, and Oracle enter the game, , Node is shedding its bad reputation of being immature and unstable. In this article, I will show you how easy it is to install Node.js on Windows.
Install Node.js

Getting Node.js installed on Windows is a piece of cake. Go to the Node.js website, download and run the ".msi" file. It will install Node.js and NPM (Node Package Management Module). NPM is equivalent For the NuGet package manager for .NET applications.

Run Node.js

Running Node.js on Windows is equally easy. Open PowerShell and type "node -v" Make sure Node is in your environment variables and see what version of Node.js you are running. Likewise type "npm -v" " Let’s check the version of the Node package management tool you installed. Are you done? Ok, let’s start having fun!!

Open the Notepad program, we will build our first Node.js application. Copy the following code into the Notepad program, use any file name, such as "example.js", and save it Go to the folder you want:

var http = require('http');
http.createServer(function (req, res) {
 res.writeHead(200, {'Content-Type': 'text/plain'});
 res.end('Hello Node');
}).listen(1337, '127.0.0.1');

Now go back to PowerShell. Change the path to where your "example.js" file is and run Node!

cd C:\Websites\NodeTest
node example.js

Open your web browser and navigate to http://127.0.0.1:1337. Did it work? Congratulations on running your first Node.js application!

Providing website services

Are you worried that I will just leave a "Hello World" example and call it a day? If we know how to run an HTML file, it will be even better. Add an "index.html" file, which can be Any HTML content. It will look like this:

<html>
 <head>
  <title>Sample Node.js Website</title>
 </head>
 <body>
  <p>This is the home page for you Node.js website.</p>
 </body>
</html>

It’s time to run the app. Create a new file with any name, such as "index.js", and add the following js code to it:

var http = require('http');
var fs = require('fs');
 
http.createServer(function(req, res){
  fs.readFile('index.html',function (err, data){
    res.writeHead(200, {
       'Content-Type': 'text/html',
       'Content-Length': data.length
      });
    res.write(data);
    res.end();
  });
}).listen(1337, '127.0.0.1');

Things start to get more interesting here. Notice the extra line "require" at the beginning. You are bringing in the required dependencies into your application. This is similar to the "require" line used in C# to call dependencies. using" namespace directive.

Run "index.js" by typing: node index.js in PowerShell (don't forget to hit Ctrl-C to exit the last Node application run, or use a new port number this time). In your browser, navigate to http://127.0.0.1:1337 and you should see your HTML file. You will probably be a little excited at this achievement, but if you miss me, just I'm going to have some mixed feelings about it. This is still low-level programming, and the world would change quickly if I had to think about reading/streaming files and what status should be sent each time. I have a lot of troubles. Say hello to ExpressJS!

Use the Node package manager

Node.js has a partner that makes the world feel beautiful again. ExpressJS blocks the need to repeat the same old tricks in Node.js, allowing you to directly enter web development. It is a tool that allows you to build single pages, A web framework for multi-page and mixed-type web applications. Without it you have no hope in the Node.js world!

First install it using NPM. To do this, open PowerShell again and switch to the path of your application. Now type: npm install express. It will create a node called "node_modules" to install ExpressJS. From this perspective As you can see, your Node modules will be placed there, kind of like the "bin" directory in a .NET application, and from here you can call or "require" your dependent programs.

Getting Started with ExpressJS

Now create a new file, such as "server.js", and paste the following code into it:

var express = require('express');
 
//CREATE APP
var app = express();
 
//LOCATION OF STATIC CONTENT IN YOUR FILESYSTEM
app.use(express.static(__dirname));
 
//PORT TO LISTEN TO
app.listen(1337);

这是在调用ExpressJS的依赖, 然后从它那里创建一个应用. 从此你可就牛逼大发了! 在这里,我们只是简单的提供静态文件服务. "__dirname" 是来自ExpressJS的一个特殊的变量,意思是根文件系统位置. 最后你告诉应用去侦听端口 1337. 现在你就拥有了一个提供静态文件服务的 Node.js 站点了! 另外在新增一些HTML文件,一些放在子目录中,然后到http://127.0.0.1:1337 测试看看吧.

关于 IIS

在这些示例中, 我一直都是在端口1337运行应用,而不是端口80.原因是IIS已经侦听了80端口. 有许多的方法可以使IIS 和 Node.js 和谐共存:

  •     IISNode: 这是一个在你的IIS站点让Node.js像一个应用池那样运行的很聪明的点子, 同在IIS中与运行PHP很像. 事实上,Azure就是用这个在其平台上运行Node.js的.
  •     WinServ: 它让 Node.js 像一个Windows服务那样运行. 它实际上是对流行了 NSSM (Non-Sucking Service Manager)的一个对Node.js友好的封装. 一旦作为一个服务运行,你就可以使用IIS的应用请求路由(ARR) 来代理向你的Node.js应用端口发起的请求.

关于 MS SQL

有许多为Node.js准备的 MS SQL 驱动程序, 有些甚至是跨平台的. 有一个只能在Windows环境中运行的,是由Windows Azure发布: Microsoft Driver for Node.js for SQL Server. 而你可以像下面这样开始工作:
 

var sql = require('node-sqlserver');
var connStr = "Driver={SQL Server Native Client 11.0};Server=(local);Database=AdventureWorks2012;Trusted_Connection={Yes}";
var cmd = "SELECT TOP 10 FirstName, LastName FROM Person.Person";
 
sql.open(connStr, function (err, conn) {
  conn.queryRaw(cmd , function (err, results) {
    for (var i = 0; i < results.rows.length; i++) {
      console.log(
          "FirstName: " + results.rows[i][0]
       + " LastName: " + results.rows[i][1]);
    }
  });
});

总结

这些都只是皮毛! 与 ExpressJS携手, 你将能够创建带有路由、视图、布局、服务还有更多组件的完全成熟的MVC应用程序. 同样,除非你需要去集成一些现有的Microsoft应用程序或者MS SQL数据库, MongoDB 在你创建一个Node堆栈式是能帮助你从SQL中解放的好伙伴. 最后,你可以使用MEAN创建一个MEAN Javascript全栈应用, 包括有MongoDB, ExpressJS, AngularJS, 和Node.js. 现在企业已经向Node.js靠拢了, 对你而言同样是不是时候来辅助行动了呢?

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.