Node常用模块简介

22次阅读

共计 5391 个字符,预计需要花费 14 分钟才能阅读完成。

Node 常用模块简介

在学习开发 node 过程中,会发现 node 不仅自己内置了相当多的工具模块,还有更多的第三方应用模块,如果你了解了这些模块的功能,在 node 的天空中就犹如插上了翅膀,因此本片文章将简要介绍一些模块的基本功能,供您快速了解每个模块的大概功能:

fs

(file system)文件系统,该模块提供了用于与文件系统进行交互的 API,并且所有的文件操作都具有同步和异步的形式。

异步读取文件:

const fs = require('fs')
fs.readFile('demo.txt','utf8',function(err,data){if(err){throw err;}
    console.log(data);
})

该方法第一个参数用于指定文件名;第二个参数指定字符编码,若没有指定则返回原始 buffer;callback 用户返回读取错误或内容,若正确读取则 err 值为 null,data 为文件的内容。

同步读取文件:

fs.readFileSync('demo.txt','utf8',function(err,data){})

使用方法同异步形式,与 fs.readFile 相似。

fs 还提供了文件流的读写操作,对于上传下载超大文件时,可以对文件进行流的读取写入操作,

let fs = require("fs");

let readStream = fs.createReadStream("./demo.js"); 

let writeStream = fs.createWriteStream("demodemo.js");

// 监听文件流打开关闭
readStream.once('open', () => {console.log('readstream opened');
})

readStream.once('clos', () => {console.log('readstream closed');
})

writeStream.once('open', () => {console.log('writeStream opened');
})

writeStream.once('clos', () => {console.log('writeStream closed');
})

// 读入流操作
readStream.on('data', (data) => {console.log(data);        //<Buffer more bytes>
    // 文件过大时分段读取
    // 写入
    writeStream.write(data);
})

path

路径模块提供了一些实用工具,用于处理文件和目录路径。

const path = require('path')

path.resolve 方法会将路径或路径片段的序列解析为绝对路径:

path.resolve('./demo.txt');
// 返回:c:\Users\Name\Desktop\promise\demo1.txt
path.resolve('./demo1.txt','./demo2.txt');
// 返回:c:\Users\Name\Desktop\promise\demo1.txt\demo2.txt

path.join 方法会将给定的 path 片段链接到一起,然后规范化生成路径。

path.join(__dirname,'./demo.txt');
//c:\Users\Name\Desktop\promise\demo.txt

http

http 模块用于创建一个能够处理和响应 http 响应的服务

const http = require("http");

// 创建一个 http 服务并监听端口
http.createServer((request, response) => {
    //request 请求对象
    //response 响应对象
    response.end('hello world');
}).listen(3000);

http.get 方法用于发起一个 GET 请求,并返回响应结果

http.get('http://www.baidu.com', (res) => {console.log(`Got response: ${res.statusCode}`);
  // consume response body
  res.resume();});
//Got response: 200

GET 方法在请求后自动调用 res.end()

querystring

查询字符串模块,用于提供解析和格式化 URL 查询字符串的工具。

querystirng.stringify 用于将制定对象序列化

querystring.stringify({foo: 'bar', baz: ['qux', 'quux'], corge: '' });
//foo=bar&baz=qux&baz=quux&corge=

该方法会序列化 string/number/boolean/[string]/[number]/[boolean] 类型的值,其他输入的值都会被强制转换为空字符串。

querystring.parse 方法用于解析 URL 查询字符串为键值对集合:

querystring.parse('foo=bar&abc=xyz&abc=123')
//{foo: 'bar', abc: [ 'xyz', '123'] }

注意:[Object: null prototype]

该方法返回的对象不是从原型继承自 Object,所以这个对象的一些方法如:obj.toString(),obj.hasOwnProperty() 都不起作用。

cheerio

cheerio 是 jquery 核心功能的一个快速灵活而又简洁的实现,主要是为了用在服务器端需要对 DOM 进行操作的地方。

const cheerio = require('cheerio');
const $ = cheerio.load('<body>...</body>');
$('ul.list li').each((index,item) => {let content = item.text();
    console.log(content)
})

首选需要加载 HTML,在 jquery 中这一步是隐式操作的,使用 cheerio 时需要手动操作一下。然后就可以像 jquery 一样正常操作 DOM 结构了。

util

util 模块是一类包罗万象的模块。它提供了实用函数来格式化字符串,将对象转换为字符串,检查对象的类型,并执行对输出流的同步写入,以及一些对象继承的增强。

util.format 格式化字符串,第一个参数为格式化字符串:

util.format('%s:%s', 'foo');
// 返回: 'foo:%s'
//%s 用于转化除 BigInt,Object,- 0 以外的所有值 

若没有参数,则不进行替换

util.promisify 可以将一个 node 常见异步方法包装成回调风格的函数,并返回一个 promise 对象

const readFile = util.promisify(fs.readFile);
readFile('./demo.txt','utf8').then((err,data) => {if(err) throw err;
    console.log(data);
}).catch(err => {//...})

promisify 的回调都会假定第一个参数为错误对象,第二个参数为正确结果,因此 promisify 只能格式化 node 的一些方法,如:fs.readFile,fs.writeFile 等

util.inspect 用于配置检查对象

depth 用于配置显示对象的深度层级:

let obj = {
    l1: {
        l2: {name: 'apple'},
        l3: 'pear',
    }
};

console.log(util.inspect(obj,{depth:0}));
console.log(util.inspect(obj,{depth:1}));
//{l1: [Object] }
//{l1: { l2: [Object], l3: 'pear' } }

util.sorted 设置为 true,则对象属性名会进行排序,如果设置一个 function 比较函数,则将被调用于排序:

let obj = {
    name: 'Amy',
    age: 14,
    birth: 1992,
    sex: 'male'
};
let r1 = inspect(obj,{sorted: true});
let r2 = inspect(obj,{sorted: compare});
function compare(a,b){if(a >= b){return -1;}
}
console.log(r1);    //{age: 14, birth: 1992, name: 'Amy', sex: 'male'}
console.log(r2);    //{sex: 'male', name: 'Amy', birth: 1992, age: 14}

crypto

该模块提供了加密功能,包括 OpenSSL 的哈希、HMAC、加密、解密、签名、以及验证功能的一整套封装。

const crypto = require('crypto')
const secret = 'abcdefg';
const hash = crypto.createHmac('sha256', secret)
                   .update('I love you')
                   .digest('hex');
console.log(hash);
//a3d7754086d8e1d921cfc85cf4b22992698e3fbbc4b3610b782580d78b73b997

url

用于处理和解析 URL。

url.parse 用于解析一个 url 地址:

const url = require('url');
const myURL =
    url.parse('https://user:pass@sub.host.com:8080/p/a/t/h?query=string#hash', true);
console.log(myURL);
// Url {
//     protocol: 'https:',
//     slashes: true,
//     auth: null,
//     host: 'www.iloveyou.com:8080',
//     port: '8080',
//     hostname: 'www.iloveyou.com',
//     hash: '#hash',
//     search: '?query=string',
//     query: [Object: null prototype] {query: 'string'},
//     pathname: '/p/a/t/h',
//     path: '/p/a/t/h?query=string',
//     href: 'https://www.iloveyou.com:8080/p/a/t/h?query=string#hash'
//   }

返回一个 URL 对象,用于描述该路径的相关信息。

反过来,可以根据一个对象生成一个地址 url:

let res = url.format({   
  protocol: 'http:',   
  host: 'www.example.com',    
  pathname: '/p/a/t/h',    
  search: 'query=string'
});
console.log(res);        //https://www.iloveyou.com:8080/a/b/c/d?query=string

url.resolve 还可以用来拼接 URL:

url.resolve('/a/b/c', 'd');  // /a/b/d
url.resolve('http://iloveyou.com/', '/one');    //http://iloveyou.com/one

将要解析的基本 URL 放到目标 URL 上,解决锚点标记 href 问题。

uuid

用于创建不同类型的 uuid,

npm install uuid

UUID Version 1:基于时间的 UUID
UUID Version 2:DCE 安全的 UUID
UUID Version 3:基于名字的 UUID(MD5)
UUID Version 4:随机 UUID
UUID Version 5:基于名字的 UUID(SHA1)

const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341';
let u1 = uuid.v1();
// let u2 = uuid.v2();  该方法未实现
let u3 = uuid.v3('hello.example.com', MY_NAMESPACE);
let u4 = uuid.v4();
let u5 = uuid.v5('hello.example.com', MY_NAMESPACE);

// dd7b8b80-c066-11ea-bf0f-8ff3a22b8c14
// f3d172e3-a128-3701-a2d0-3d38eac3b538
// bdbb54c2-aadc-4bf8-9b09-83a10219d19d
// 0c7ffc8d-5990-59b0-a870-cb70e59f183a

nodemon

node 自动重启工具,可以用来监控 node 源代码的任何变化,并自动重启你的服务器,可以使用 npm 来进行全局安装。

npm install -g nodemon

使用时,在命令行中配置要运行的文件路径即可:

nodemon ./server.js localhost 8080

同时还可以配置主机名和端口

还有哪些您想知道或推荐的模块呢,欢迎下方留言,小编将择期撰写相关文章哦~

正文完
 0