Node.js 可以解析 JS 代码(没有浏览器安全级别的限制)提供很多系统级别的 API,如:
- 文件的读写 (File System)
- 进程的管理 (Process)
- 网络通信 (HTTP/HTTPS)
- …
网络请求
1 2 3 4 5 6 7 8 9 10 11 12 13
| const https = require("https");
https.get("https://obsidianstar.cn/2021/05/26/nodeJs/node-api/", res => { let str = "";
res.on("data", chunk => { str += chunk; });
res.on("end", () => { console.log(str); }); });
|
文件的读写 (File System)
1 2 3 4 5 6 7 8 9 10 11 12
| const fs = require("fs");
fs.readFile("./ajax.png", "utf-8", (err, content) => { console.log(content); });
fs.writeFile("./log.txt", "hello", (err, data) => { if (err) { } else { console.log("文件创建成功"); } });
|
进程的管理(Process)
1 2 3 4 5
| function main(argv) { console.log(argv); }
main(process.argv.slice(2));
|
运行
1
| node 2.3-process.js argv1 argv2
|
网络通信(HTTP/HTTPS)
1 2 3 4 5 6 7 8 9 10 11 12
| const http = require("http");
const server = http.createServer((request, response) => { let url = request.url;
response.write(url); response.end(); });
server.listen("3000", "localhost", () => { console.log("localhost:3000"); });
|