Home > Web Front-end > JS Tutorial > A simple introductory tutorial for Node.js under Windows system_node.js

A simple introductory tutorial for Node.js under Windows system_node.js

WBOY
Release: 2016-05-16 15:53:27
Original
1644 people have browsed it

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');
Copy after login

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
Copy after login

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>
Copy after login

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');
Copy after login

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);
Copy after login

这是在调用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]);
    }
  });
});
Copy after login

总结

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template