
Node.js 入门的主线很清楚:它能在浏览器之外运行 JavaScript,并提供文件、进程、网络通信等系统级 API。 源文覆盖范围很大,从第一个 HTTP 服务写到 CommonJS、npm、fs、静态 Web、EJS、MongoDB
Node.js 入门的主线很清楚:它能在浏览器之外运行 JavaScript,并提供文件、进程、网络通信等系统级 API。
源文覆盖范围很大,从第一个 HTTP 服务写到 CommonJS、npm、fs、静态 Web、EJS、MongoDB、Express、Koa、Cookie、Session 和 JavaScript 继承。本文把它整理成后端学习路线。
http.createServer,理解 request 和 response 后,再看路由和静态资源。require 引入模块,用 exports 或 module.exports 暴露能力。fs 模块负责文件和目录操作,异步 API 要注意回调执行时机。适合已经会基础 JavaScript,准备学习 Node.js 后端开发的人。
如果你要的是 TypeScript、NestJS、工程化测试或生产部署,这篇不覆盖。
第一层是运行时能力:HTTP、URL、文件读写、流。
第二层是模块和包:CommonJS、npm、package.json、依赖安装。
第三层是 Web 能力:静态资源、路由、模板引擎、GET 和 POST。
第四层是框架:Express 中间件、Cookie、Session、路由模块化、文件上传、Mongoose;Koa 路由、中间件、async/await、静态资源和模板。
第五层是数据库和语言补充:MongoDB、聚合管道、JavaScript 继承和单例。
源文从 Node 内置 http 模块开始:
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World1111');
}).listen(8081);
console.log('Server running at http://127.0.0.1:8081/');
再进一步,可以设置 HTML 响应头和字符集,避免中文乱码。
const http = require('http');
http.createServer((req, res) => {
console.log(req.url);
res.writeHead(200, { 'Content-type': 'text/html;charset=utf-8' });
res.write("<head><meta charset='UTF-8'></head>");
res.write('小老弟');
res.end();
}).listen(3000);
url 模块可以解析查询参数。
const url = require('url');
var api = 'http://www.baidu.com?name=zhangsan&age=19';
var getvalue = url.parse(api, true).query;
console.log(getvalue);
源文把模块分为核心模块和自定义模块。HTTP、URL、fs 都是 Node.js 内置核心模块,可以直接引入。
自定义模块默认不会把内部属性和方法暴露给外部,必须通过 exports 或 module.exports。
exports.get = function () {
console.log('获取数据');
};
exports.post = function () {
console.log('提交数据');
};
使用时通过相对路径引入:
var request = require('./module/request');
console.log(request);
npm 部分的重点是 package.json。源文建议每个项目根目录都有 package.json,安装包时保存依赖信息。
npm init --yes
npm install md5 --save
npm install
源文列出了常用文件系统 API:
| 操作 | API |
|---|---|
| 检测文件或目录 | fs.stat |
| 创建目录 | fs.mkdir |
| 写入文件 | fs.writeFile |
| 追加文件 | fs.appendFile |
| 读取文件 | fs.readFile |
| 读取目录 | fs.readdir |
| 重命名或移动 | fs.rename |
| 删除目录 | fs.rmdir |
| 删除文件 | fs.unlink |
读文件示例:
const fs = require('fs');
fs.readFile('./html/index.html', (err, data) => {
if (err) {
console.log(err);
return;
}
console.log(data.toString());
});
流适合处理文件读写和复制。
const fs = require('fs');
var readStream = fs.createReadStream('./1.jpg');
var writeStream = fs.createWriteStream('./data/1.jpg');
readStream.pipe(writeStream);
源文还记录了一个异步陷阱:找出文件夹下所有目录时,如果先 console.log,数组可能还没收集完。这个问题要用回调、Promise、async/await 或递归流程控制解决。
静态服务器的核心步骤是:解析路径,映射默认首页,读取静态文件,按后缀返回 MIME 类型。
const http = require('http');
const fs = require('fs');
const path = require('path');
const url = require('url');
const common = require('./module/common.js');
http.createServer(function (req, res) {
let pathname = url.parse(req.url).pathname;
pathname = pathname == '/' ? '/index.html' : pathname;
let extname = path.extname(pathname);
if (pathname != '/favicon.ico') {
fs.readFile('./static' + pathname, async (err, data) => {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/html;charset="utf-8"' });
res.end('404');
return;
}
let mime = await common.getFilename(extname);
res.writeHead(200, { 'Content-Type': mime + ';charset="utf-8"' });
res.end(data);
});
}
}).listen(3000);
源文后面把静态服务封装成 routes.static(req, res, 'static'),这就是从脚本走向框架的第一步。
Express 部分从基本使用、EJS、GET/POST、中间件、Cookie、Session、路由模块化、上传图片和 Mongoose 展开。
源文对 GET 和 POST 的区分很直接:GET 一般用于获取数据,POST 一般用于提交数据。
app.get('/', function(req, res) {
res.send('hello world');
});
app.post('/', function(req, res) {
res.send('hello world');
});
Koa 部分强调 async/await 和中间件执行顺序。
var Koa = require('koa');
var app = new Koa();
app.use(async (ctx) => {
ctx.body = 'hello,koa';
});
app.listen(3000);
Koa 路由示例:
var router = require('koa-router')();
router
.get('/', async (ctx) => {
ctx.body = '你好';
})
.get('/news/:aid/:cid', async (ctx) => {
console.log(ctx.params);
ctx.body = '新闻';
});
源文的中间件例子说明:app.use 先执行,await next() 后继续向下匹配路由,回来后还能处理 404 或打印日志。
MongoDB 部分包含关系型和非关系型数据库对比、数据库基本操作、索引、管理员权限、聚合管道、备份恢复和 Node.js 操作 MongoDB。
聚合管道涉及这些操作符:
$project$match$group$sort$limit$skip$lookupKoa 中连接 MongoDB 的示例:
var MongoClient = require('mongodb').MongoClient;
var dbUrl = 'mongodb://127.0.0.1:27017/';
var dbName = 'koa';
MongoClient.connect(dbUrl, (err, client) => {
if (err) {
console.log(err);
return;
}
var db = client.db(dbName);
db.collection('user').insertOne({
username: 'dd',
age: 29,
sex: '男',
status: '1'
}, (err) => {
if (!err) {
console.log('连接成功');
client.close();
}
});
});
源文后半部分整理了原型链继承、对象冒充继承、混合继承、寄生式组合继承和 ES6 class extends。
其中 ES6 写法更适合初学者建立直觉:
function Father(name, age) {
this.name = name;
this.age = age;
}
class Son extends Father {
constructor(name, age, sex) {
super(name);
this.age = age;
this.sex = sex;
}
f2() {
console.log('我是自定义的子级方法');
}
}
源文也记录了单例模式:通过静态方法缓存实例,保证多次调用拿到同一个对象。
源文是大而全的学习笔记,本文没有复述所有命令和截图。MongoDB、Express、Koa、Mongoose、Cookie、Session 都只保留了学习框架和代表性代码。
源文中的部分示例偏早期 CommonJS 写法,本文没有改写为 ES Module 或 TypeScript。
fs 写一个静态资源服务,按文件后缀返回 MIME。AWS在Amazon Bedrock AgentCore上推出Web Search API,开发者通过签名API即可联网搜索,无需自建网关或额外资源,可从AWS SDK或CLI调用,适用于应用、Agent循环和数据管道。这体现云厂商将Agent外围能力API化的趋势,降低集成运维成本,但定价、配额等约束仍需核实。
今日AI动态聚焦基础设施与落地实践:llama.cpp新增TTS端点、实时转录API并扩展嵌入模型,强化服务端多模态能力;Vercel AI SDK优化导入性能与流处理。东南亚数字经济报告显示AI推动区域增长,企业AI原生开发流程成为热点。
今日AI领域开源基础设施与硬件生态双重变奏:DocumentDB 1.0与ggml 1.0发布标志开源数据与推理栈走向成熟,llama.cpp密集更新带来5-10%性能提升;英伟达则因涉嫌人为制造GPU稀缺、黄仁勋离职引发融资缩水及董事抛售股票而面临信任考验,开发者工具链持续打磨健壮性。
新内容发布后发送确认邮件,不会把未验证或已退订地址加入发送列表。
欢迎理性讨论与补充勘误
无需登录即可评论,展示名称会使用脱敏 IP。
暂无评论