node.js的常用内置库共128节
Node.js 的常用内置库非常广泛,但是如果我们仅仅讨论常见的、核心的库,那么主要可以分为以下几类:
- 文件系统(File System)
- 模块系统(Modules)
- 网络(HTTP, HTTPS, TCP, DNS)
- 流(Stream)
- 加密(Crypto)
- 调试(Debugger, Console)
- 进程(Process)
- 文本解析(JSON, XML, CSV)
- 错误处理(Error Handling)
- 事件(Events)
- 缓冲区(Buffer)
- 路径(Path)
- 查询字符串(Query String)
- 时间(Timeouts, Timers)
- zlib(Compression)
- 加载器(Module Loader)
这里我将为每一类提供一个简单的示例代码。
- 文件系统(File System)
const fs = require('fs');
fs.readFile('example.txt', (err, data) => {
if (err) throw err;
console.log(data);
});
- 模块系统(Modules)
// math.js
exports.add = function(a, b) {
return a + b;
};
// main.js
const math = require('./math.js');
console.log(math.add(1, 1)); // 2
- 网络(HTTP, HTTPS, TCP, DNS)
const http = require('http');
http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(3000, () => {
console.log('Server running at http://127.0.0.1:3000/');
});
- 流(Stream)
const fs = require('fs');
const readableStream = fs.createReadStream('example.txt');
const writableStream = fs.createWriteStream('example_copy.txt');
readableStream.pipe(writableStream);
- 加密(Crypto)
const crypto = require('crypto');
const hash = crypto.createHash('sha256');
hash.update('Hello World');
console.log(hash.digest('hex')); // e794657labs870ad936da363394f5ca329dn31ff1d71390bd7a35ddb69f4
- 调试(Debugger, Console)
const console = require('console');
const myConsole = new console.Console(process.stdout, process.stderr);
myConsole.log('Hello World!');
- 进程(Process)
const process = require('process');
process.on('exit', () => {
console.log('Bye!');
});
- 文本解析(JSON, XML, CSV)
const JSON = require('json');
const obj = { name: 'John', age: 31, city: 'New York' };
const myJSON = JSON.stringify(obj);
console.log(myJSON);
- 错误处理(Error Handling)
const fs = require('fs');
fs.readFile('example.txt', (err, data) => {
评论已关闭