promise
的函数 。Util
模块还可以帮助处理一些常见模式,诸如解码文本、类型检查和检查对象 。
- 【有用的内置Node.js APIs】
util.callbackify(function)
:接收一个返回promise
的函数,并返回一个基于回调的函数 。
util.isDeepStrictEqual(object1, object2)
:当两个对象严格相等(所有子属性必须匹配)时返回true
。
util.format(format, [args])
:返回一个使用类printf格式的字符串 。
util.inspect(object, options)
:返回一个对象的字符串表示,用于调试 。与使用console.dir(object, { depth: null, color: true });
类似 。
util.stripVTControlCharacters(str)
:剥离字符串中的ANSI转义代码 。
util.types
:为常用的JavaScript和Node.js值提供类型检查 。比如:
import util from 'util';util.types.isDate( new Date() ); // trueutil.types.isMap( new Map() );// trueutil.types.isRegExp( /abc/ ); // trueutil.types.isAsyncFunction( async () => {} ); // true
{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
的函数,这使得管理异步文件操作更加容易 。你将经常把
fs
和path
结合起来使用,以解决不同操作系统上的文件名问题 。下面的例子模块使用
stat
和access
方法返回一个有关文件系统对象的信息:// 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 = [];
经验总结扩展阅读
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- 飞机上可以带辣椒酱吗
- 经济价值高的树种有哪些 世界十大经济树木排名榜
- 可乐鸡翅没有料酒可以用什么代替
- 芒果皮有毒吗
- 原神没有课题的答案任务是什么
- 冰箱里一定有李斯特菌吗
- 学蛋糕甜点适合在哪里学
- 3.5l的砂锅有多大
- 冻干免煮银耳羹还有营养吗?
- 红葱头的吃法