有用的内置Node.js APIs( 二 )


import util from 'util';util.types.isDate( new Date() ); // trueutil.types.isMap( new Map() );// trueutil.types.isRegExp( /abc/ ); // trueutil.types.isAsyncFunction( async () => {} ); // trueURLURL是另一个全局对象,可以让你安全地创建、解析以及修改web URL 。它对于从URL中快速提取协议、端口、参数和哈希值非常有用 , 而不需要借助于正则 。比如:
{href: 'https://example.org:8000/path/?abc=123#target',origin: 'https://example.org:8000',protocol: 'https:',username: '',password: '',host: 'example.org:8000',hostname: 'example.org',port: '8000',pathname: '/path/',search: '?abc=123',searchParams: URLSearchParams { 'abc' => '123' },hash: '#target'}你可以查看并更改任意属性 。比如:
myURL.port = 8001;console.log( myURL.href );// https://example.org:8001/path/?abc=123#target然后可以使用URLSearchParams API修改查询字符串值 。比如:
myURL.searchParams.delete('abc');myURL.searchParams.append('xyz', 987);console.log( myURL.search );// ?xyz=987还有一些方法可以将文件系统路径转换为URL,然后再转换回来 。
dns模块提供名称解析功能 , 因此你可以查询IP地址、名称服务器、TXT记录和其他域名信息 。
File System APIfs API可以创建、读取、更新以及删除文件、目录以及权限 。最近发布的Node.js运行时在fs/promises中提供了基于promise的函数,这使得管理异步文件操作更加容易 。
你将经常把fspath结合起来使用 , 以解决不同操作系统上的文件名问题 。
下面的例子模块使用stataccess方法返回一个有关文件系统对象的信息:
// fetch file informationimport { constants as fsConstants } from 'fs';import { access, stat } from 'fs/promises';export async function getFileInfo(file) {const fileInfo = {};try {const info = await stat(file);fileInfo.isFile = info.isFile();fileInfo.isDir = info.isDirectory();}catch (e) {return { new: true };}try {await access(file, fsConstants.R_OK);fileInfo.canRead = true;}catch (e) {}try {await access(file, fsConstants.W_OK);fileInfo.canWrite = true;}catch (e) {}return fileInfo;}当传递一个文件名时,该函数返回一个包含该文件信息的对象 。比如:
{isFile: true,isDir: false,canRead: true,canWrite: true}filecompress.js主脚本使用path.resolve()将命令行上传递的输入和输出文件名解析为绝对文件路径,然后使用上面的getFileInfo()获取信息:
#!/usr/bin/env nodeimport path from 'path';import { readFile, writeFile } from 'fs/promises';import { getFileInfo } from './lib/fileinfo.js';// check filesletinput = path.resolve(process.argv[2] || ''),output = path.resolve(process.argv[3] || ''),[ inputInfo, outputInfo ] = await Promise.all([ getFileInfo(input), getFileInfo(output) ]),error = [];上述代码用于验证路径,必要时以错误信息终止:
// use input file name when output is a directoryif (outputInfo.isDir && outputInfo.canWrite && inputInfo.isFile) {output = path.resolve(output, path.basename(input));}// check for errorsif (!inputInfo.isFile || !inputInfo.canRead) error.push(`cannot read input file ${ input }`);if (input === output) error.push('input and output files cannot be the same');if (error.length) {console.log('Usage: ./filecompress.js [input file] [output file|dir]');console.error('\n' + error.join('\n'));process.exit(1);}然后用readFile()将整个文件读成一个名为content的字符串:
// read fileconsole.log(`processing ${ input }`);let content;try {content = await readFile(input, { encoding: 'utf8' });}catch (e) {console.log(e);process.exit(1);}let lengthOrig = content.length;console.log(`file size${ lengthOrig }`);然后JavaScript正则表达式会删除注释和空格:
// compress contentcontent = content.replace(/\n\s+/g, '\n')// trim leading space from lines.replace(/\/\/.*?\n/g, '')// remove inline // comments.replace(/\s+/g, ' ')// remove whitespace.replace(/\/\*.*?\*\//g, '')// remove /* comments */.replace(/<!--.*?-->/g, '')// remove <!-- comments -->.replace(/\s*([<>(){}}[\]])\s*/g, '$1') // remove space around brackets.trim();let lengthNew = content.length;产生的字符串用writeFile()输出到一个文件,并有一个状态信息展示保存情况:
let lengthNew = content.length;// write fileconsole.log(`outputting ${output}`);console.log(`file size${ lengthNew } - saved ${ Math.round((lengthOrig - lengthNew) / lengthOrig * 100) }%`);try {content = await writeFile(output, content);}catch (e) {console.log(e);process.exit(1);}使用示例HTML文件运行项目代码:

推荐阅读