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();



执行查看结果:

 

  • 6
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值