Node.js® 是一个基于 Chrome V8 引擎 的 JavaScript 运行时环境。
我们知道,在浏览器中可以运行JavaScript脚本,这是因为浏览器包含了JavaScript的解析引擎,其中 V8 就是Chrome浏览器的JS解析引擎。那么,如果有独立的、非浏览器内嵌的JS解析引擎,则JavaScript代码不就可以独立运行,不受限于浏览器了吗?Node.js正是基于这一点应运而生,其本质仍然是JavaScript,只不过它基于V8引擎,提供了JavaScript所需的运行环境。
下载地址:https://nodejs.org/en/
我下载的文件是 node-v16.15.1-linux-x64.tar.xz 。把文件解压,生成 node-v16.15.1-linux-x64 目录,把其下的 bin 目录加到 PATH 里。我是用的 zsh ,所以修改 ~/.zshrc 配置文件,添加:
export PATH="/home/ding/Downloads/node-v16.15.1-linux-x64/bin:$PATH"
现在,就可以使用node命令了,比如:
➜ ~ node -v
v16.15.1
创建文件 0727_1.js :
console.log('hello world');
运行程序:
➜ temp0727 node 0727_1.js
hello world
创建文件 0727_2.js :
const http = require('http');
const server = http.createServer();
server.on('request', (req, res) => {
console.log('hello');
res.end('OK\n');
});
server.listen(8080, () => {
console.log('server started');
});
运行程序,启动服务器:
➜ temp0727 node 0727_2.js
server started
打开另一个命令行,访问服务器:
➜ ~ curl http://localhost:8080
OK
可见,得到了期望的“OK”响应。同时服务器的console也输出了“hello”:
➜ temp0727 node 0727_2.js
server started
hello
按Ctrl + C停止服务器。
创建文件 0727_3.js :
const http = require('http');
const server = http.createServer();
server.on('request', (req, res) => {
console.log('hello');
res.end('hi, 你好\n');
});
server.listen(8080, () => {
console.log('server started');
});
在命令行下,用 curl 命令可以正确的显式:
➜ ~ curl http://localhost:8080
hi, 你好
但是在浏览器中会显示为乱码:

解决办法是添加如下代码:
......
res.setHeader('Content-Type', 'text/html; charset=utf-8');
......
重新启动服务,现在浏览器中显示也OK了:

可使用请求的 url 属性来区分不同的请求。
创建文件 0727_4.js :
const http = require('http');
const server = http.createServer();
server.on('request', (req, res) => {
console.log('hello');
const url = req.url;
var content = '';
if (url === '/a.html') {
content = '床前明月光\n';
} else if (url === '/b.html') {
content = '白日依山尽\n';
}
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.end(content);
});
server.listen(8080, () => {
console.log('server started');
});
运行程序,访问服务器,如下:
➜ ~ curl http://localhost:8080/a.html
床前明月光
➜ ~ curl http://localhost:8080/b.html
白日依山尽
可见,对不同的请求有不同的处理。
https://nodejs.org/en/https://nodejs.org/zh-cn/ (中文)