在第一部分 Node.js 基础知识中,主要是以下内容。为了方便起见,我还为每个部分提供了一些简短的代码示例。
1. Node.js 简介
* 介绍 Node.js 的历史、特点和用途。
2. JavaScript 语法回顾
* 变量声明与数据类型(例如:`const`, `let`)
* 函数(例如:箭头函数)
* 对象和数组(例如:字面量表示法)
* 循环和条件语句(例如:`for`, `while`, `if-else`)
3. Node.js 模块系统
* CommonJS 规范
* `require()` 函数和 `module.exports`
// math.js
module.exports = {
add: (a, b) => a + b,
multiply: (a, b) => a * b,
};
// index.js
const math = require('./math');
console.log(math.add(1, 2));
console.log(math.multiply(3, 4));
4. 事件驱动和异步编程
* 事件循环
* 异步回调
* Promise 和 async/await
const fs = require('fs');
// 使用回调函数
fs.readFile('file.txt', 'utf-8', (err, data) => {
if (err) throw err;
console.log(data);
});
// 使用 Promise 和 async/await
const readFileAsync = (path, encoding) => {
return new Promise((resolve, reject) => {
fs.readFile(path, encoding, (err, data) => {
if (err) reject(err);
resolve(data);
});
});
};
(async () => {
try {
const data = await readFileAsync('file.txt', 'utf-8');
console.log(data);
} catch (err) {
console.error(err);
}
})();
5. 创建简单的 HTTP 服务器
* `http` 模块
* 请求和响应对象
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, Node.js!');
});
server.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});