nodejs api学习:fs.createWriteStream()

作用

上一篇博客介绍了createReadSream()函数,用于读取一个可读的文件流,接下来介绍一个作用与之相反的函数:createWriteStream(),有读取操作就有写入操作,改函数的作用就是对文件流进行写入

参数

参数与createReadSream函数同样:


/*
@params:path指定文件的路径
@params:options可选,是一个JS对象,可以指定一些选项如:
let option={
              flags: 'w',//指定用什么模式打开文件,’w’代表写,’r’代表读,类似的还有’r+’、’w+’、’a’等
              encoding: 'utf8',//指定打开文件时使用编码格式,默认就是“utf8”,你还可以为它指定”ascii”或”base64”
              fd: null,//fd属性默认为null,当你指定了这个属性时,createReadableStream会根据传入的fd创建一个流,忽略path。另外你要是想读取一个文件的特定区域,可以配置start、end属性,指定起始和结束(包含在内)的字节偏移
              mode: 0666,
              autoClose: true//autoClose属性为true(默认行为)时,当发生错误或文件读取结束时会自动关闭文件描述符
          }
 

返回对象

ReadStream {
  _readableState:
   ReadableState {
     objectMode: false,
     highWaterMark: 65536,
     buffer: BufferList { head: null, tail: null, length: 0 },
     length: 0,
     pipes: null,
     pipesCount: 0,
     flowing: null,
     ended: false,
     endEmitted: false,
     reading: false,
     sync: true,
     needReadable: false,
     emittedReadable: false,
     readableListening: false,
     resumeScheduled: false,
     destroyed: false,
     defaultEncoding: 'utf8',
     awaitDrain: 0,
     readingMore: false,
     decoder:
      StringDecoder {
        encoding: 'utf8',
        fillLast: [Function: utf8FillLast],
        lastNeed: 0,
        lastTotal: 0,
        lastChar: <Buffer 00 00 38 6a> },
     encoding: 'utf8' },
  readable: true,
  domain: null,
  _events: { end: [Function] },
  _eventsCount: 1,
  _maxListeners: undefined,
  path: './test/b.js',
  fd: null,
  flags: 'r',
  mode: 438,
  start: undefined,
  end: undefined,
  autoClose: true,
  pos: undefined,
  bytesRead: 0 }

常用事件


const fs=require('fs');
const path=require('path');
let writeStream=fs.createWriteStream('./test/b.js',{encoding:'utf8'});





//读取文件发生错误事件
writeStream.on('error', (err) => {
    console.log('发生异常:', err);
});
//已打开要写入的文件事件
writeStream.on('open', (fd) => {
    console.log('文件已打开:', fd);
});
//文件已经就写入完成事件
writeStream.on('finish', () => {
    console.log('写入已完成..');
    console.log('读取文件内容:', fs.readFileSync('./test/b.js', 'utf8')); //打印写入的内容
    console.log(writeStream);
});

//文件关闭事件
writeStream.on('close', () => {
    console.log('文件已关闭!');
});

writeStream.write('这是我要做的测试内容');
writeStream.end();



执行查看结果:

猜你喜欢

转载自blog.csdn.net/Buddha_ITXiong/article/details/81199173