NodeJS常用API

node.js中文网http://nodejs.cn/api/

(path、Buffer、events、fs)

①path路径-----const {resolve} = require('path');

  • path.normalize(path);//规范化指定的 path,并处理 '..' 和 '.' 片段
path.normalize('C:\\temp\\\\foo\\bar\\..\\');
// 返回: 'C:\\temp\\foo\\'
  • path.join([...paths]);//使用平台特定的分隔符把所有 path 片段连接到一起,并规范化生成的路径

path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
// 返回: '/foo/bar/baz/asdf'
  • path.resolve([...paths]);//将路径或路径片段的序列处理成绝对路径

path.resolve('/foo/bar', './baz');
// 返回: '/foo/bar/baz'
  • path.basename(path[, ext]);//返回 path 的最后一部分,类似于 Unix 中的 basename 命令

path.basename('/foo/bar/baz/asdf/quux.html');
// 返回: 'quux.html'
  • path.extname(path);//返回 path 的扩展名,即从 path 的最后一部分中的最后一个 .(句号)字符到字符串结束

path.extname('index.html');
// 返回: '.html'

path.extname('index.coffee.md');
// 返回: '.md'
  • path.dirname(path);//返回 path 的目录名,类似于 Unix 中的 dirname 命令

path.dirname('/foo/bar/baz/asdf/quux');
// 返回: '/foo/bar/baz/asdf'
  • path.sep;//返回平台特定的路径片段分隔符

'foo\\bar\\baz'.split(path.sep);
// 返回: ['foo', 'bar', 'baz']
  • path.delimiter;//返回平台特定的路径分隔符

console.log(process.env.PATH);
// 输出: 'C:\Windows\system32;C:\Windows;C:\Program Files\node\'

process.env.PATH.split(path.delimiter);
// 返回: ['C:\\Windows\\system32', 'C:\\Windows', 'C:\\Program Files\\node\\']
  • path.win32;//返回为 Windows 实现的 path 方法

  • path.posix;//返回为 POSIX 实现的 path 方法

区别:

  • _dirname、_filename总返回文件的绝对路径
  • process.cwd( )返回执行node命令所在文件夹
  • ./或者../
    • 在require方法中总是相对当前文件所在文件夹
    • 在其他地方和process.cwd( )一样,相对node启动文件

②Buffer缓冲

  • 用于处理二进制数据流
  • 实例类似整数数组,大小固定
  • c++代码在V8堆外分配物理内存

1)初始化

  • Buffer.alloc(size[, fill[, encoding]]);//创建一个大小为 size 字节的 Buffer

const buf = Buffer.alloc(5, 'a');
console.log(buf);
// 输出: <Buffer 61 61 61 61 61>
  • Buffer.allocUnsafe(size);//创建一个大小为 size 字节的 Buffer,Buffer的内容是未知的

const buf = Buffer.allocUnsafe(10);
console.log(buf);
// 输出: <Buffer a0 8b 28 3f 01 00 00 00 50 32>
// (输出的内容是内存的旧数据,每次都不同)
  • Buffer.from(array);//使用字节数组 array 创建 Buffer

// 创建一个包含字符串 'buffer' 的 UTF-8 字节的 Buffer。
const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
  • Buffer.from(string[, encoding]);//创建一个包含 string 的 Buffer

const buf1 = Buffer.from('this is a tést');
const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');
console.log(buf1.toString());
// 输出: this is a tést
console.log(buf2.toString());
// 输出: this is a tést
console.log(buf1.toString('ascii'));
// 输出: this is a tC)st

2)类

  • Buffer.byteLength(string[, encoding]);//返回字符串的实际字节长度

const str = '\u00bd + \u00bc = \u00be';
console.log(`${str}: ${str.length} 个字符,` +`${Buffer.byteLength(str, 'utf8')} 个字节`);
// 输出: ½ + ¼ = ¾: 9 个字符, 12 个字节
  • Buffer.concat(list[, totalLength]);//返回一个合并了 list 中所有 Buffer 的新 Buffer

// 用含有三个 `Buffer` 的数组创建一个单一的 `Buffer`。
const buf1 = Buffer.alloc(10);
const buf2 = Buffer.alloc(14);
const totalLength = buf1.length + buf2.length;
console.log(totalLength);
// 输出: 24
const bufA = Buffer.concat([buf1, buf2], totalLength);
console.log(bufA);
// 输出: <Buffer 00 00 00 00 ...>
console.log(bufA.length);
// 输出: 24
  • Buffer.isBuffer(obj);//如果 obj 是一个 Buffer,则返回 true,否则返回 false

3)实例-----const buf = Buffer.from('This is a test!');

  • buf.length;//回内存中分配给 buf 的字节数

const buf = Buffer.alloc(1234);
console.log(buf.length);
// 输出: 1234
  • buf.toString([encoding[, start[, end]]]);//根据 encoding 指定的字符编码将 buf 解码成字符串

const buf = Buffer.from('tést');
console.log(buf.toString('hex'));
// 输出: 74c3a97374
console.log(buf.toString('utf8', 0, 3));
// 输出: té
  • buf.fill(value[, offset[, end]][, encoding]);//用指定的 value 填充 buf

// 用 ASCII 字符 'h' 填充 `Buffer`。
const b = Buffer.allocUnsafe(50).fill('h');
console.log(b.toString());
// 输出: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
  • buf.equals(otherBuffer);//如果 buf 与 otherBuffer 具有完全相同的字节,则返回 true,否则返回 false

const buf1 = Buffer.from('ABC');
const buf2 = Buffer.from('414243', 'hex');
const buf3 = Buffer.from('ABCD');
console.log(buf1.equals(buf2));
// 输出: true
console.log(buf1.equals(buf3));
// 输出: false
  • buf.indexOf(value[, byteOffset][, encoding]);//返回buf 中首次出现 value 的索引,如果 buf 没包含 value 则返回 -1

const buf = Buffer.from('this is a buffer');
console.log(buf.indexOf('this'));
// 输出: 0
console.log(buf.indexOf('is'));
// 输出: 2
  • buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]]);//拷贝 buf 中某个区域的数据到 target 中的某个区域,即使 target 的内存区域与 buf 的重叠

// 创建两个 `Buffer`。
const buf1 = Buffer.allocUnsafe(26);
const buf2 = Buffer.allocUnsafe(26).fill('!');
for (let i = 0; i < 26; i++) {
  // 97 是 'a' 的十进制 ASCII 值。
  buf1[i] = i + 97;
}
// 拷贝 `buf1` 中第 16 至 19 字节偏移量的数据到 `buf2` 第 8 字节偏移量开始。
buf1.copy(buf2, 8, 16, 20);
console.log(buf2.toString('ascii', 0, 25));
// 输出: !!!!!!!!qrst!!!!!!!!!!!!!

4)字符串解码器-----string_decoder 模块提供了一个 API,用于把 Buffer 对象解码成字符串

const { StringDecoder } = require('string_decoder');
const decoder = new StringDecoder('utf8');

const cent = Buffer.from([0xC2, 0xA2]);
console.log(decoder.write(cent));

③events事件-----const EventEmitter = require('events');//所有能触发时间的对象都是EventEmitter类的实例

  • emitter.on(eventName, listener);//添加 listener 函数到名为 eventName 的事件的监听器数组的末尾,注册监听器

const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
//   b
//   a
  • emitter.emit(eventName[, ...args]);//按照监听器注册的顺序,同步地调用每个注册到名为 eventName 的事件的监听器,并传入提供的参数,触发事件

  • emitter.once(eventName, listener);//添加单次监听器 listener 到名为 eventName 的事件

  • emitter.removeListener(eventName, listener);//从名为 eventName 的事件的监听器数组中移除指定的 listener

  • emitter.removeAllListeners([eventName]);//移除全部监听器或指定的 eventName 事件的监听器

④fs文件系统-----const fs = require('fs');

1)读

  • fs.readFile(path[, options], callback);//异步地读取文件的内容

fs.readFile('/etc/passwd', 'utf8', callback);
fs.readFile(
'/etc/passwd', (err, data) => { if (err) throw err; console.log(data); });
  • fs.readFileSync(path[, options]);//同步返回文件的内容,同步比异步快,但是会阻塞

2)写

  • fs.writeFile(file, data[, options], callback);//异步地将数据写入文件,如果文件已存在,则覆盖文件
fs.writeFile('文件.txt', '内容', 'utf8', callback);

const data = new Uint8Array(Buffer.from('Node.js中文网'));
fs.writeFile('文件.txt', data, (err) => {
  if (err) throw err;
  console.log('文件已保存');
});

3)状态

  • fs.stat(path[, options], callback);//异步查看文件的属性

fs.stat('文件路径', (err, stats) => {
  if (err) throw err;
  console.log(stats.isFile( ));//文件
  console.log(stats.isDirectory( ));//文件夹
  console.log(stats);//状态
});

4)重命名

  • fs.rename(oldPath, newPath, callback);//异步地把文件 oldPath 重命名为 newPath

fs.rename('旧文件.txt', '新文件.txt', (err) => {
  if (err) throw err;
  console.log('已完成重命名');
});

5)删除

  • fs.unlink(path, callback);//异步地移除一个文件或符号链接

// 假设 'path/file.txt' 是一个普通文件。
fs.unlink('path/file.txt', (err) => {
  if (err) throw err;
  console.log('文件已删除');
});
  • fs.readdir(path[, options], callback);//异步读取目录(文件夹)的内容

  • fs.mkdir(path[, options], callback);//异步地创建目录

// 创建 /tmp/a/apple 目录,不管 `/tmp` 和 /tmp/a 目录是否存在。
fs.mkdir('/tmp/a/apple', { recursive: true }, (err) => {
  if (err) throw err;
});
  • fs.rmdir(path, callback);//异步地删除目录

  • fs.watch(filename[, options][, listener]);//监视 filename 的变化,filename 可以是一个文件或一个目录

6)流(有向传输数据)

  • const rs = fs.creatReadStream('路径');
    • rs.pipe(process.stout);
  • const ws = fs.creatWriteStream('路径');
    • ws.write('字符串');
    • ws.end( );

7)解决回调地狱(异步回调里有回调,回调里又有回调......)

const util = require('util');
const fs = require('fs');

const stat = util.promisify(fs.stat);
stat('.').then((stats) => {
  // Do something with `stats`
}).catch((error) => {
  // Handle the error.
});
const util = require('util');
const fs = require('fs');

const stat = util.promisify(fs.stat);

async function callStat() {
  const stats = await stat('.');
  console.log(`This directory is owned by ${stats.uid}`);
}
posted @ 2018-11-29 19:50  M-M-Monica  阅读(1105)  评论(0)    收藏  举报