Node学习笔记大全(二)

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 文件模块相同的方法列表:

序号方法 & 描述
1fs.rename(oldPath, newPath, callback)
异步 rename().回调函数没有参数,但可能抛出异常。
2fs.ftruncate(fd, len, callback)
异步 ftruncate().回调函数没有参数,但可能抛出异常。
3fs.ftruncateSync(fd, len)
同步 ftruncate()
4fs.truncate(path, len, callback)
异步 truncate().回调函数没有参数,但可能抛出异常。
5fs.truncateSync(path, len)
同步 truncate()
6fs.chown(path, uid, gid, callback)
异步 chown().回调函数没有参数,但可能抛出异常。
7fs.chownSync(path, uid, gid)
同步 chown()
8fs.fchown(fd, uid, gid, callback)
异步 fchown().回调函数没有参数,但可能抛出异常。
9fs.fchownSync(fd, uid, gid)
同步 fchown()
10fs.lchown(path, uid, gid, callback)
异步 lchown().回调函数没有参数,但可能抛出异常。
11fs.lchownSync(path, uid, gid)
同步 lchown()
12fs.chmod(path, mode, callback)
异步 chmod().回调函数没有参数,但可能抛出异常。
13fs.chmodSync(path, mode)
同步 chmod().
14fs.fchmod(fd, mode, callback)
异步 fchmod().回调函数没有参数,但可能抛出异常。
15fs.fchmodSync(fd, mode)
同步 fchmod().
16fs.lchmod(path, mode, callback)
异步 lchmod().回调函数没有参数,但可能抛出异常。Only available on Mac OS X.
17fs.lchmodSync(path, mode)
同步 lchmod().
18fs.stat(path, callback)
异步 stat(). 回调函数有两个参数 err, stats,stats 是 fs.Stats 对象。
19fs.lstat(path, callback)
异步 lstat(). 回调函数有两个参数 err, stats,stats 是 fs.Stats 对象。
20fs.fstat(fd, callback)
异步 fstat(). 回调函数有两个参数 err, stats,stats 是 fs.Stats 对象。
21fs.statSync(path)
同步 stat(). 返回 fs.Stats 的实例。
22fs.lstatSync(path)
同步 lstat(). 返回 fs.Stats 的实例。
23fs.fstatSync(fd)
同步 fstat(). 返回 fs.Stats 的实例。
24fs.link(srcpath, dstpath, callback)
异步 link().回调函数没有参数,但可能抛出异常。
25fs.linkSync(srcpath, dstpath)
同步 link().
26fs.symlink(srcpath, dstpath[, type], callback)
异步 symlink().回调函数没有参数,但可能抛出异常。 type 参数可以设置为 'dir', 'file', 或 'junction' (默认为 'file') 。
27fs.symlinkSync(srcpath, dstpath[, type])
同步 symlink().
28fs.readlink(path, callback)
异步 readlink(). 回调函数有两个参数 err, linkString。
29fs.realpath(path[, cache], callback)
异步 realpath(). 回调函数有两个参数 err, resolvedPath。
30fs.realpathSync(path[, cache])
同步 realpath()。返回绝对路径。
31fs.unlink(path, callback)
异步 unlink().回调函数没有参数,但可能抛出异常。
32fs.unlinkSync(path)
同步 unlink().
33fs.rmdir(path, callback)
异步 rmdir().回调函数没有参数,但可能抛出异常。
34fs.rmdirSync(path)
同步 rmdir().
35fs.mkdir(path[, mode], callback)
S异步 mkdir(2).回调函数没有参数,但可能抛出异常。 访问权限默认为 0777。
36fs.mkdirSync(path[, mode])
同步 mkdir().
37fs.readdir(path, callback)
异步 readdir(3). 读取目录的内容。
38fs.readdirSync(path)
同步 readdir().返回文件数组列表。
39fs.close(fd, callback)
异步 close().回调函数没有参数,但可能抛出异常。
40fs.closeSync(fd)
同步 close().
41fs.open(path, flags[, mode], callback)
异步打开文件。
42fs.openSync(path, flags[, mode])
同步 version of fs.open().
43fs.utimes(path, atime, mtime, callback)
 
44fs.utimesSync(path, atime, mtime)
修改文件时间戳,文件通过指定的文件路径。
45fs.futimes(fd, atime, mtime, callback)
 
46fs.futimesSync(fd, atime, mtime)
修改文件时间戳,通过文件描述符指定。
47fs.fsync(fd, callback)
异步 fsync.回调函数没有参数,但可能抛出异常。
48fs.fsyncSync(fd)
同步 fsync.
49fs.write(fd, buffer, offset, length[, position], callback)
将缓冲区内容写入到通过文件描述符指定的文件。
50fs.write(fd, data[, position[, encoding]], callback)
通过文件描述符 fd 写入文件内容。
51fs.writeSync(fd, buffer, offset, length[, position])
同步版的 fs.write()。
52fs.writeSync(fd, data[, position[, encoding]])
同步版的 fs.write().
53fs.read(fd, buffer, offset, length, position, callback)
通过文件描述符 fd 读取文件内容。
54fs.readSync(fd, buffer, offset, length, position)
同步版的 fs.read.
55fs.readFile(filename[, options], callback)
异步读取文件内容。
56fs.readFileSync(filename[, options])
57fs.writeFile(filename, data[, options], callback)
异步写入文件内容。
58fs.writeFileSync(filename, data[, options])
同步版的 fs.writeFile。
59fs.appendFile(filename, data[, options], callback)
异步追加文件内容。
60fs.appendFileSync(filename, data[, options])
The 同步 version of fs.appendFile.
61fs.watchFile(filename[, options], listener)
查看文件的修改。
62fs.unwatchFile(filename[, listener])
停止查看 filename 的修改。
63fs.watch(filename[, options][, listener])
查看 filename 的修改,filename 可以是文件或目录。返回 fs.FSWatcher 对象。
64fs.exists(path, callback)
检测给定的路径是否存在。
65fs.existsSync(path)
同步版的 fs.exists.
66fs.access(path[, mode], callback)
测试指定路径用户权限。
67fs.accessSync(path[, mode])
同步版的 fs.access。
68fs.createReadStream(path[, options])
返回ReadStream 对象。
69fs.createWriteStream(path[, options])
返回 WriteStream 对象。
70fs.symlink(srcpath, dstpath[, type], callback)
异步 symlink().回调函数没有参数,但可能抛出异常。

Node.js 工具模块

在 Node.js 模块库中有很多好用的模块。接下来我们为大家介绍几种常用模块的使用:

序号模块名 & 描述
1OS模块
提供基本的系统操作函数。
2Path模块
提供了处理和转换文件路径的工具。
3Net模块
用于底层的网络通信。提供了服务端和客户端的的操作。
4DNS模块
用于解析域名。
5Domin模块
简化异步代码的异常处理,可以捕捉处理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();


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

**之火

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值