Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行时环境,它让开发者可以在服务器端运行 JavaScript 代码。本教程将介绍 Node.js 的基本 API,帮助您快速上手。
快速开始
以下是一些 Node.js 的基本 API:
- 模块系统: Node.js 使用 CommonJS 模块系统。您可以使用
require()
函数来导入模块。
const http = require('http');
http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, world!\n');
}).listen(8000);
console.log('Server running at http://localhost:8000/');
- 文件系统: Node.js 提供了一个强大的文件系统 API,可以用来读写文件。
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
return console.error(err);
}
console.log(data);
});
fs.writeFile('example.txt', 'Hello, world!', (err) => {
if (err) {
return console.error(err);
}
console.log('File written successfully');
});
- 网络编程: Node.js 提供了
http
模块,可以用来创建 Web 服务器。
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, world!\n');
});
server.listen(8000, () => {
console.log('Server running at http://localhost:8000/');
});
更多资源
如果您想了解更多关于 Node.js 的信息,可以访问以下链接:
Node.js Logo