Node.js常用工具
util是一个Node.js核心模块,提供常用功能的集合,用于替换核心JavaScript的功能过于精简的不足。
使用方法如下:
const util = require('util ');
util.callbackify
util.callbackify(original) 将async
初始化函数(或者一个返回变量Promise
的函数)转换成相应的异常优先级的样式风格的函数,例如将(err, value) => ...
成为最后一个参数。在函数中,第一个参数为拒绝的原因(如果Promise
解决,则为null
),第二个参数则是解决的值。
实用程序继承
util.inherits(constructor,superConstructor)是一个实现对象间原型继承的函数。
实用程序检查
util.inspect(object,[showHidden],[depth],[colors])是一个将任意对象转换为字符串的方法,通常用于调试和错误输出。它至少接受一个参数object,即要转换的对象。
util.isArray(对象)
如果给定的参数“ object”是一个重复返回true,否则返回false。
util.isRegExp(对象)
如果给定的参数“ object”是一个正则表达式返回true,否则返回false。
util.isDate(对象)
如果给定的参数“ object”是一个日期返回true,否则返回false。
Node.js 文件系统
var fs = require("fs")
文件模块方法参考手册
以下为 Node.js 文件模块相同的方法列表:
序号 | 方法 & 描述 |
---|---|
1 | fs.rename(oldPath, newPath, callback) 异步 rename().回调函数没有参数,但可能抛出异常。 |
2 | fs.ftruncate(fd, len, callback) 异步 ftruncate().回调函数没有参数,但可能抛出异常。 |
3 | fs.ftruncateSync(fd, len) 同步 ftruncate() |
4 | fs.truncate(path, len, callback) 异步 truncate().回调函数没有参数,但可能抛出异常。 |
5 | fs.truncateSync(path, len) 同步 truncate() |
6 | fs.chown(path, uid, gid, callback) 异步 chown().回调函数没有参数,但可能抛出异常。 |
7 | fs.chownSync(path, uid, gid) 同步 chown() |
8 | fs.fchown(fd, uid, gid, callback) 异步 fchown().回调函数没有参数,但可能抛出异常。 |
9 | fs.fchownSync(fd, uid, gid) 同步 fchown() |
10 | fs.lchown(path, uid, gid, callback) 异步 lchown().回调函数没有参数,但可能抛出异常。 |
11 | fs.lchownSync(path, uid, gid) 同步 lchown() |
12 | fs.chmod(path, mode, callback) 异步 chmod().回调函数没有参数,但可能抛出异常。 |
13 | fs.chmodSync(path, mode) 同步 chmod(). |
14 | fs.fchmod(fd, mode, callback) 异步 fchmod().回调函数没有参数,但可能抛出异常。 |
15 | fs.fchmodSync(fd, mode) 同步 fchmod(). |
16 | fs.lchmod(path, mode, callback) 异步 lchmod().回调函数没有参数,但可能抛出异常。Only available on Mac OS X. |
17 | fs.lchmodSync(path, mode) 同步 lchmod(). |
18 | fs.stat(path, callback) 异步 stat(). 回调函数有两个参数 err, stats,stats 是 fs.Stats 对象。 |
19 | fs.lstat(path, callback) 异步 lstat(). 回调函数有两个参数 err, stats,stats 是 fs.Stats 对象。 |
20 | fs.fstat(fd, callback) 异步 fstat(). 回调函数有两个参数 err, stats,stats 是 fs.Stats 对象。 |
21 | fs.statSync(path) 同步 stat(). 返回 fs.Stats 的实例。 |
22 | fs.lstatSync(path) 同步 lstat(). 返回 fs.Stats 的实例。 |
23 | fs.fstatSync(fd) 同步 fstat(). 返回 fs.Stats 的实例。 |
24 | fs.link(srcpath, dstpath, callback) 异步 link().回调函数没有参数,但可能抛出异常。 |
25 | fs.linkSync(srcpath, dstpath) 同步 link(). |
26 | fs.symlink(srcpath, dstpath[, type], callback) 异步 symlink().回调函数没有参数,但可能抛出异常。 type 参数可以设置为 'dir', 'file', 或 'junction' (默认为 'file') 。 |
27 | fs.symlinkSync(srcpath, dstpath[, type]) 同步 symlink(). |
28 | fs.readlink(path, callback) 异步 readlink(). 回调函数有两个参数 err, linkString。 |
29 | fs.realpath(path[, cache], callback) 异步 realpath(). 回调函数有两个参数 err, resolvedPath。 |
30 | fs.realpathSync(path[, cache]) 同步 realpath()。返回绝对路径。 |
31 | fs.unlink(path, callback) 异步 unlink().回调函数没有参数,但可能抛出异常。 |
32 | fs.unlinkSync(path) 同步 unlink(). |
33 | fs.rmdir(path, callback) 异步 rmdir().回调函数没有参数,但可能抛出异常。 |
34 | fs.rmdirSync(path) 同步 rmdir(). |
35 | fs.mkdir(path[, mode], callback) S异步 mkdir(2).回调函数没有参数,但可能抛出异常。 访问权限默认为 0777。 |
36 | fs.mkdirSync(path[, mode]) 同步 mkdir(). |
37 | fs.readdir(path, callback) 异步 readdir(3). 读取目录的内容。 |
38 | fs.readdirSync(path) 同步 readdir().返回文件数组列表。 |
39 | fs.close(fd, callback) 异步 close().回调函数没有参数,但可能抛出异常。 |
40 | fs.closeSync(fd) 同步 close(). |
41 | fs.open(path, flags[, mode], callback) 异步打开文件。 |
42 | fs.openSync(path, flags[, mode]) 同步 version of fs.open(). |
43 | fs.utimes(path, atime, mtime, callback) |
44 | fs.utimesSync(path, atime, mtime) 修改文件时间戳,文件通过指定的文件路径。 |
45 | fs.futimes(fd, atime, mtime, callback) |
46 | fs.futimesSync(fd, atime, mtime) 修改文件时间戳,通过文件描述符指定。 |
47 | fs.fsync(fd, callback) 异步 fsync.回调函数没有参数,但可能抛出异常。 |
48 | fs.fsyncSync(fd) 同步 fsync. |
49 | fs.write(fd, buffer, offset, length[, position], callback) 将缓冲区内容写入到通过文件描述符指定的文件。 |
50 | fs.write(fd, data[, position[, encoding]], callback) 通过文件描述符 fd 写入文件内容。 |
51 | fs.writeSync(fd, buffer, offset, length[, position]) 同步版的 fs.write()。 |
52 | fs.writeSync(fd, data[, position[, encoding]]) 同步版的 fs.write(). |
53 | fs.read(fd, buffer, offset, length, position, callback) 通过文件描述符 fd 读取文件内容。 |
54 | fs.readSync(fd, buffer, offset, length, position) 同步版的 fs.read. |
55 | fs.readFile(filename[, options], callback) 异步读取文件内容。 |
56 | fs.readFileSync(filename[, options]) |
57 | fs.writeFile(filename, data[, options], callback) 异步写入文件内容。 |
58 | fs.writeFileSync(filename, data[, options]) 同步版的 fs.writeFile。 |
59 | fs.appendFile(filename, data[, options], callback) 异步追加文件内容。 |
60 | fs.appendFileSync(filename, data[, options]) The 同步 version of fs.appendFile. |
61 | fs.watchFile(filename[, options], listener) 查看文件的修改。 |
62 | fs.unwatchFile(filename[, listener]) 停止查看 filename 的修改。 |
63 | fs.watch(filename[, options][, listener]) 查看 filename 的修改,filename 可以是文件或目录。返回 fs.FSWatcher 对象。 |
64 | fs.exists(path, callback) 检测给定的路径是否存在。 |
65 | fs.existsSync(path) 同步版的 fs.exists. |
66 | fs.access(path[, mode], callback) 测试指定路径用户权限。 |
67 | fs.accessSync(path[, mode]) 同步版的 fs.access。 |
68 | fs.createReadStream(path[, options]) 返回ReadStream 对象。 |
69 | fs.createWriteStream(path[, options]) 返回 WriteStream 对象。 |
70 | fs.symlink(srcpath, dstpath[, type], callback) 异步 symlink().回调函数没有参数,但可能抛出异常。 |
Node.js 工具模块
在 Node.js 模块库中有很多好用的模块。接下来我们为大家介绍几种常用模块的使用:
序号 | 模块名 & 描述 |
---|---|
1 | OS模块 提供基本的系统操作函数。 |
2 | Path模块 提供了处理和转换文件路径的工具。 |
3 | Net模块 用于底层的网络通信。提供了服务端和客户端的的操作。 |
4 | DNS模块 用于解析域名。 |
5 | Domin模块 简化异步代码的异常处理,可以捕捉处理try catch无法捕捉的。 |
Node.js Web 模块
什么是 Web 服务器?
Web服务器一般指网站服务器,是指驻留于因特网上某种类型计算机的程序,Web服务器的基本功能就是提供Web信息浏览服务。它只需支持HTTP协议、HTML文档格式及URL,与客户端的网络浏览器配合。
大多数 web 服务器都支持服务端的脚本语言(php、python、ruby)等,并通过脚本语言从数据库获取数据,将结果返回给客户端浏览器。
目前最主流的三个Web服务器是Apache、Nginx、IIS。
Web 应用架构
-
Client - 客户端,一般指浏览器,浏览器可以通过 HTTP 协议向服务器请求数据。
-
Server - 服务端,一般指 Web 服务器,可以接收客户端请求,并向客户端发送响应数据。
-
Business - 业务层, 通过 Web 服务器处理应用程序,如与数据库交互,逻辑运算,调用外部程序等。
-
Data - 数据层,一般由数据库组成。
使用 Node 创建 Web 服务器
实例
var http = require('http');
var fs = require('fs');
var url = require('url');
// 创建服务器
http.createServer( function (request, response) {
// 解析请求,包括文件名
var pathname = url.parse(request.url).pathname;
// 输出请求的文件名 console.log("Request for " + pathname + " received.");
// 从文件系统中读取请求的文件内容
fs.readFile(pathname.substr(1), function (err, data) { if (err) { console.log(err);
// HTTP 状态码: 404 : NOT FOUND
// Content Type: text/html
response.writeHead(404, {'Content-Type': 'text/html'});
}else{
// HTTP 状态码: 200 : OK
// Content Type: text/html
response.writeHead(200, {'Content-Type': 'text/html'});
// 响应文件内容
response.write(data.toString());
}
// 发送响应数据
response.end();
});
}).listen(8080);
// 控制台会输出以下信息
console.log('Server running at http://127.0.0.1:8080/');
Node.js Express 框架
Express 简介
Express 是一个简洁而灵活的 node.js Web应用框架, 提供了一系列强大特性帮助你创建各种 Web 应用,和丰富的 HTTP 工具。
使用 Express 可以快速地搭建一个完整功能的网站。
Express 框架核心特性:
-
可以设置中间件来响应 HTTP 请求。
-
定义了路由表用于执行不同的 HTTP 请求动作。
-
可以通过向模板传递参数来动态渲染 HTML 页面。
Node.js 多进程
我们都知道 Node.js 是以单线程的模式运行的,但它使用的是事件驱动来处理并发,这样有助于我们在多核 cpu 的系统上创建多个子进程,从而提高性能。
每个子进程总是带有三个流对象:child.stdin, child.stdout 和child.stderr。他们可能会共享父进程的 stdio 流,或者也可以是独立的被导流的流对象。
Node 提供了 child_process 模块来创建子进程,方法有:
-
exec - child_process.exec 使用子进程执行命令,缓存子进程的输出,并将子进程的输出以回调函数参数的形式返回。
-
spawn - child_process.spawn 使用指定的命令行参数创建新进程。
-
fork - child_process.fork 是 spawn()的特殊形式,用于在子进程中运行的模块,如 fork('./son.js') 相当于 spawn('node', ['./son.js']) 。与spawn方法不同的是,fork会在父进程与子进程之间,建立一个通信管道,用于进程之间的通信。
Node.js 连接 MySQL
创建连接查询示例
var mysql = require('mysql');
var connection = mysql.createConnection({ host : 'localhost', user : 'root', password : '123456', database : 'test' });
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
Node.js 连接 MongoDB
MongoDB是一种文档导向数据库管理系统,由C++撰写而成。
//创建连接
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/runoob";
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
console.log("数据库已创建!");
db.close();
});
//创建集合
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/runoob';
MongoClient.connect(url, { useNewUrlParser: true }, function (err, db) {
if (err) throw err;
console.log('数据库已创建');
var dbase = db.db("runoob");
dbase.createCollection('site', function (err, res) {
if (err) throw err;
console.log("创建集合!");
db.close();
});
});
//插入一条数据
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("runoob");
var myobj = { name: "菜鸟教程", url: "www.runoob" };
dbo.collection("site").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log("文档插入成功");
db.close();
});
});
//插入多条数据
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("runoob");
var myobj = [
{ name: '菜鸟工具', url: 'https://c.runoob.com', type: 'cn'},
{ name: 'Google', url: 'https://www.google.com', type: 'en'},
{ name: 'Facebook', url: 'https://www.google.com', type: 'en'}
];
dbo.collection("site").insertMany(myobj, function(err, res) {
if (err) throw err;
console.log("插入的文档数量为: " + res.insertedCount);
db.close();
});
});
//查询指定条件的数据
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("runoob");
var whereStr = {"name":'菜鸟教程'}; // 查询条件
dbo.collection("site").find(whereStr).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
//更新一条/多条数据
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("runoob");
var whereStr = {"name":'菜鸟教程'}; // 查询条件
var updateStr = {$set: { "url" : "https://www.runoob.com" }};
//如果要更新所有符合条的文档数据可以使用 updateMany():
dbo.collection("site").updateOne(whereStr, updateStr, function(err, res) {
if (err) throw err;
console.log("文档更新成功");
db.close();
});
});
//删除一条/多条数据
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("runoob");
var whereStr = {"name":'菜鸟教程'}; // 查询条件
//如果要删除多条语句可以使用 deleteMany() 方法
dbo.collection("site").deleteOne(whereStr, function(err, obj) {
if (err) throw err;
console.log("文档删除成功");
db.close();
});
});
//排序
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("runoob");
//{ type: 1 } // 按 type 字段升序
//{ type: -1 } // 按 type 字段降序
var mysort = { type: 1 };
dbo.collection("site").find().sort(mysort).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
//limit():读取两条数据
//skip(): 跳过前面两条数据,读取两条数据
写法:dbo.collection("site").find().skip(2).limit(2).toArray(function(err, result)
//连接操作
//mongoDB 不是一个关系型数据库,但我们可以使用 $lookup 来实现左连接
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://127.0.0.1:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("runoob");
dbo.collection('orders').aggregate([
{ $lookup:
{
from: 'products', // 右集合
localField: 'product_id', // 左集合 join 字段
foreignField: '_id', // 右集合 join 字段
as: 'orderdetails' // 新生成字段(类型array)
}
}
]).toArray(function(err, res) {
if (err) throw err;
console.log(JSON.stringify(res));
db.close();
});
});
//使用 drop() 方法来删除集合
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("runoob");
// 删除 test 集合
dbo.collection("test").drop(function(err, delOK) {
// 执行成功 delOK 返回 true,否则返回 false
if (err) throw err;
if (delOK) console.log("集合已删除");
db.close();
});
});
Promise 是一个 ECMAScript 6 提供的类,目的是更加优雅地书写复杂的异步任务。
//以下实例使用 Promise 创建集合:
const MongoClient = require("mongodb").MongoClient;
const url = "mongodb://localhost/runoob";
MongoClient.connect(url).then((conn) => {
console.log("数据库已连接");
var dbase = conn.db("runoob");
dbase.createCollection("site").then((res) => {
console.log("已创建集合");
}).catch((err) => {
console.log("数据库操作错误");
}).finally(() => {
conn.close();
});
}).catch((err) => {
console.log("数据库连接失败");
});
//实现四个连续操作:增加 、查询 、更改 、删除
const MongoClient = require("mongodb").MongoClient;
const url = "mongodb://localhost/";
MongoClient.connect(url).then((conn) => {
console.log("数据库已连接");
const test = conn.db("testdb").collection("test");
// 增加
test.insertOne({ "site": "runoob.com" }).then((res) => {
// 查询
return test.find().toArray().then((arr) => {
console.log(arr);
});
}).then(() => {
// 更改
return test.updateMany({ "site": "runoob.com" },
{ $set: { "site": "example.com" } });
}).then((res) => {
// 查询
return test.find().toArray().then((arr) => {
console.log(arr);
});
}).then(() => {
// 删除
return test.deleteMany({ "site": "example.com" });
}).then((res) => {
// 查询
return test.find().toArray().then((arr) => {
console.log(arr);
});
}).catch((err) => {
console.log("数据操作失败" + err.message);
}).finally(() => {
conn.close();
});
}).catch((err) => {
console.log("数据库连接失败");
});
//用异步函数实现相同的数据操作
const MongoClient = require("mongodb").MongoClient;
const url = "mongodb://localhost/";
async function dataOperate() {
var conn = null;
try {
conn = await MongoClient.connect(url);
console.log("数据库已连接");
const test = conn.db("testdb").collection("test");
// 增加
await test.insertOne({ "site": "runoob.com" });
// 查询
var arr = await test.find().toArray();
console.log(arr);
// 更改
await test.updateMany({ "site": "runoob.com" },
{ $set: { "site": "example.com" } });
// 查询
arr = await test.find().toArray();
console.log(arr);
// 删除
await test.deleteMany({ "site": "example.com" });
// 查询
arr = await test.find().toArray();
console.log(arr);
} catch (err) {
console.log("错误:" + err.message);
} finally {
if (conn != null) conn.close();
}
}
dataOperate();