search
HomeWeb Front-endJS TutorialNodejs learning item【Getting Started】_node.js

1. Installation

First, go to http://nodejs.org to download and install. The version I downloaded is 0.8.14. Installation is very simple, just take the next step. Then configure the installation directory in the path, and msi will install npm (Node Package Manager) together.

Nodejs learning item【Getting Started】_node.js

My installation directory is C:Program Files (x86)nodejs. At this time, use the cmd command window node -v and the npm -v command to check the installed version

1.1, helloworld

Create a new file hello.js in the Node.js project directory and type a line of code in it

console.log('hello, nodejs.') ;

Enter the command line console, enter the Node.js project directory and type node hello.js

The console output "hello, nodejs."

1.2, web version of helloworld

Create a new http.js in the Node.js project directory, the code is as follows

var http = require("http");
http.createServer(function(request, response) {
 response.writeHead(200, {"Content-Type": "text/html"});
 response.write("Hello World!");
 response.end();
}).listen(8000);

Start the service in the command line and type node http.js

Then open the browser address bar and enter http://localhost:8000/. When you see Hello World! output on the page, it is successful.

The version of node.js must be synchronized with the API

The version numbers of node.js are regular. Even-numbered versions are stable versions, and odd-numbered versions are unstable versions

2 HelloWorld code analysis

Okay, let’s analyze our HelloWorld line by line from now on.

Introduction module

var http = require("http");

The require method is used to introduce a module, and the parameter is the name of the module. For example, the File System module can be introduced like this:

var fs = require("fs");

We can use the require() method as a global method, but in fact it is more like a local method belonging to a certain module. Its documentation is here: https://nodejs.org/api/globals.html.

The require method returns an instance of a certain module. For example, require("http") returns an HTTP instance. The reference documentation for HTTP examples is here: https://nodejs.org/api/http.html.

We see that the HTTP module has a method createServer(), which involves our second line of code.

Create Server

The createServer() method of the HTTP module accepts a method as a parameter, and the prototype is:

http.createServer([requestListener])

requestListener is a method that is associated with the request event of the http.Server class. In this way, when the client request arrives, the requestListener will be called.

requestListener has two parameters, and the function prototype is as follows:

function (request, response) { }

The type of the first parameter request is http.IncomingMessage, which implements the Readable Stream interface.
The type of the second parameter is http.ServerResponse, which implements the Writeable Stream interface.

Stream’s API is here: https://nodejs.org/api/stream.html. At the same time, request and response are also EventEmitters, which can emit specific events.

The API of EventEmitter is here: https://nodejs.org/api/events.html#events_class_events_eventemitter. Later we will talk about how to use EventEmitter to emit and process events.

Let’s review the code we created the server:

http.createServer(
 function(request, response) { 
  response.writeHead(200, {"Content-Type": "text/plain"}); 
  response.write("Hello World!"); 
  response.end(); 
 }
).listen(8000); 

http.createServer returns an http.Server instance. The listen method of http.Server allows the server to listen on a certain port, which is 8000 in the example.

As you can see, we provide an anonymous function to the createServer method. In this method, we write back the "Hello World!" message to the client through the response parameter.

Analyze client requests

We analyzed the http.createServer method earlier. Its parameter is a method with two parameters, one representing the request sent by the client, and the other representing the response to be written back to the client. Let's take a look at the request parameters.

request is an instance of http.IncomingMessage. Through this instance, we can get the request parameters, such as HTTP method, HTTP version, url, header, etc. The specific API is here: https://nodejs.org/api /http.html#http_http_incomingmessage.

Let’s take a look by modifying HelloWorld.js (save as HelloWorld2.js). The code is as follows:

// 引入http模块
var http = require("http"); 

// 创建server,指定处理客户端请求的函数
http.createServer(
 function(request, response) { 
  console.log("method - " + request.method);
  console.log("version - " + request.httpVersion);
  console.log("url - " + request.url);
  response.writeHead(200, {"Content-Type": "text/plain"}); 
  response.write("Hello World!"); 
  response.end(); 
 }
).listen(8000); 

console.log("Hello World start listen on port 8000");

如你所见,我使用console这个对象来输出了一些调试信息,打印了HTTP方法、版本、url等信息。可以执行node HelloWorld2.js,浏览器访问http://localhost:8000,然后跑到命令行看看输出了什么信息,我这里是这样的:

Nodejs learning item【Getting Started】_node.js

我们简简单单的HelloWorld已经可以发送一些响应数据给客户端,你在浏览器里能看到“Hello World!”字样。这个响应是通过http.ServerResponse的实例response发送给客户端的。

http.ServerResponse也是一个Stream,还是一个EventEmitter。我们通过它给客户度返回HTTP状态码、数据、HTTP头部等信息。

HTTP模块
在Node.js的HTTP模块,状态行就是通过http.ServerResponse的writeHead方法写给客户端的。writeHead方法原型如下:

response.writeHead(statusCode[, statusMessage][, headers])

这个方法的第一个参数,就是statusCode,也就是200、403之类的数字,剩下的参数是可选的。最后一个参数是headers,你可以在这里使用JSON对象表示法来写一些HTTP头部,比如:{“Content-Type”:”text/plain”,”Content-Length”:11}。第一个可选参数statusMessage用来指定一个状态描述消息,可以不填写。

HTTP头部

头部就是一些key-value对,比如我们在HelloWorld里看到的”Content-Type”,就是用来说明数据类型的头部标签,对应的可能是文本文件、图片、视频、二进制等。类似的还有”Content-Length”,用来指定数据长度。还有很多很多,比如”Date”、”Connection”等。具体还是参考前面的链接吧。

头部还可以使用http.ServerResponse的response.setHeader(name, value)方法来单独设置,一次可以设置一个HTTP头部。

数据

头部之后就是数据了,有些状态码,比如200,后续都会有一些数据。而有些,比如301、404、403、500之类的,多数没有数据。

数据通过http.ServerResponse的write方法来写回给客户端,比如这样:

response.setHeader("Content-Type", "text/html");

这里要提一点,HTTP常见的数据传输编码方式有两种:

设置Content-Length,传输固定长度的数据设置Transfer-Encoding头部为chunked,分块传输数据

像我们现在的HelloWorld示例,没有设置Content-Length头部,Node.js的HTTP模块就默认为chunked编码。

我们使用Chrome浏览器的开发者工具来查看网络数据,可以很明确的看到。如下图所示:

Nodejs learning item【Getting Started】_node.js

HTTP响应

我标注出来的三处,都是HelloWorld示例传递给浏览器的HTTP头部信息。

我们通过http.ServerResponse的write方法向客户端写数据。你可以一次写入所有数据,也可以把数据分开来多次写入。当要传输的数据量较大时,分多次写入就是比较合理的做法,比如你向客户端发送大文件,就比较适合分多次写入,也可以利用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
Vercel是什么?怎么部署Node服务?Vercel是什么?怎么部署Node服务?May 07, 2022 pm 09:34 PM

Vercel是什么?本篇文章带大家了解一下Vercel,并介绍一下在Vercel中部署 Node 服务的方法,希望对大家有所帮助!

node.js gm是什么node.js gm是什么Jul 12, 2022 pm 06:28 PM

gm是基于node.js的图片处理插件,它封装了图片处理工具GraphicsMagick(GM)和ImageMagick(IM),可使用spawn的方式调用。gm插件不是node默认安装的,需执行“npm install gm -S”进行安装才可使用。

火了!新的JavaScript运行时:Bun,性能完爆Node火了!新的JavaScript运行时:Bun,性能完爆NodeJul 15, 2022 pm 02:03 PM

今天跟大家介绍一个最新开源的 javaScript 运行时:Bun.js。比 Node.js 快三倍,新 JavaScript 运行时 Bun 火了!

聊聊Node.js中的多进程和多线程聊聊Node.js中的多进程和多线程Jul 25, 2022 pm 07:45 PM

大家都知道 Node.js 是单线程的,却不知它也提供了多进(线)程模块来加速处理一些特殊任务,本文便带领大家了解下 Node.js 的多进(线)程,希望对大家有所帮助!

node爬取数据实例:聊聊怎么抓取小说章节node爬取数据实例:聊聊怎么抓取小说章节May 02, 2022 am 10:00 AM

node怎么爬取数据?下面本篇文章给大家分享一个node爬虫实例,聊聊利用node抓取小说章节的方法,希望对大家有所帮助!

nodejs中lts是什么意思nodejs中lts是什么意思Jun 29, 2022 pm 03:30 PM

在nodejs中,lts是长期支持的意思,是“Long Time Support”的缩写;Node有奇数版本和偶数版本两条发布流程线,当一个奇数版本发布后,最近的一个偶数版本会立即进入LTS维护计划,一直持续18个月,在之后会有12个月的延长维护期,lts期间可以支持“bug fix”变更。

深入浅析Nodejs中的net模块深入浅析Nodejs中的net模块Apr 11, 2022 pm 08:40 PM

本篇文章带大家带大家了解一下Nodejs中的net模块,希望对大家有所帮助!

怎么获取Node性能监控指标?获取方法分享怎么获取Node性能监控指标?获取方法分享Apr 19, 2022 pm 09:25 PM

怎么获取Node性能监控指标?本篇文章来和大家聊聊Node性能监控指标获取方法,希望对大家有所帮助!

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!