Node.js 相关

不会 Node.js 的人已经不配再做 Web 狗了

Node

Node.js 是运行在服务端的 Javascript。使用 PHP 时,Apache 或者 Nginx 作为 HTTP 服务器,并使用 mode_php5 和 php-cgi 模块,接受 HTTP 请求并提供 Web 页面的过程不需要 PHP 处理。而使用 Node.js 时,我们不仅是在实现一个应用,同时也实现了整个 HTTP 服务器。

Node.js 应用由以下几部分组成:

  • 引入 required 模块:通过 require载入模块
  • 创建服务器:服务器可以监听客户端的请求,类似于 Apache 等 HTTP 服务器
  • 接受请求与响应请求:客户端可以使用浏览器或终端发送 HTTP 请求,服务器接收请求后返回响应数据。

创建 Node.js 应用

引入 required 模块

1
var http = require("http");

创建服务器

使用 http.createServer 方法创建服务器,使用 listen 方法指定 8888 端口,函数通过 request, response 接受和响应数据。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var http = require('http');

http.createServer(function (request, response) {

// 发送 HTTP 头部
// HTTP 状态值: 200 : OK
// 内容类型: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});

// 发送响应数据 "Hello World"
response.end('Hello World\n');
}).listen(8888);

// 终端打印如下信息
console.log('Server running at http://127.0.0.1:8888/');

使用 node 命令执行:

1
node server.js

NPM

NPM 是随 Node 安装的包管理工具

1
2
3
npm install <package> 		# 班底安装包
npm install <package> -g # 全局安装包
npm uninstall <package> # 卸载包

Node.js REPL(交互式解释器)

使用 node 进入REPL

回调函数

Node.js 具有异步特性,通过回调函数来实现

事件循环

作者

lll

发布于

2020-08-21

更新于

2022-09-19

许可协议