Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行时环境,它允许开发者使用 JavaScript 代码来编写服务器端应用程序。以下是 Node.js 的一些核心特性:
特性列表
- 非阻塞 I/O
- 事件循环
- 模块化
- 异步编程
- 文件系统
- HTTP 服务器
非阻塞 I/O
Node.js 使用非阻塞 I/O 模型,这意味着它不会等待某个操作完成后再继续执行。这种模型使得 Node.js 能够同时处理大量并发连接。
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, world!\n');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
事件循环
Node.js 使用事件循环来处理异步操作。当某个异步操作完成时,事件循环会将相应的回调函数放入事件队列中,然后依次执行。
const fs = require('fs');
fs.readFile('example.txt', (err, data) => {
if (err) throw err;
console.log(data.toString());
});
模块化
Node.js 使用 CommonJS 模块系统来组织代码。每个文件都是一个模块,可以通过 require
函数导入其他模块。
// module.js
module.exports = {
name: 'Node.js',
version: '14.17.0'
};
// otherModule.js
const module = require('./module');
console.log(module.name); // Node.js
异步编程
Node.js 的异步编程通常使用回调函数或 Promise 来实现。
// 回调函数
const fs = require('fs');
fs.readFile('example.txt', (err, data) => {
if (err) throw err;
console.log(data.toString());
});
// Promise
const fs = require('fs').promises;
async function readData() {
try {
const data = await fs.readFile('example.txt');
console.log(data.toString());
} catch (err) {
console.error(err);
}
}
readData();
文件系统
Node.js 提供了一个强大的文件系统模块,用于处理文件和目录。
const fs = require('fs');
// 创建文件
fs.writeFile('example.txt', 'Hello, world!', (err) => {
if (err) throw err;
console.log('File written successfully');
});
// 读取文件
fs.readFile('example.txt', (err, data) => {
if (err) throw err;
console.log(data.toString());
});
// 删除文件
fs.unlink('example.txt', (err) => {
if (err) throw err;
console.log('File deleted successfully');
});
HTTP 服务器
Node.js 可以轻松地创建 HTTP 服务器。
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, world!\n');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
更多关于 Node.js 的信息,请访问我们的Node.js 教程。