首页 > 一个关于Node文件读写的问题,为什么fs.createWriteStream不能用了?

一个关于Node文件读写的问题,为什么fs.createWriteStream不能用了?

前几天写的一个程序里,用了类似于这样的一段代码:

fs.createReadStream('./template/pc.ftl')
        .pipe(
            //....
        )
        .pipe(fs.createWriteStream('./template/abc.ftl'));

当时测试了很多遍,都是可以运行的
今天突然不能写了,具体表现为,abc.ftl内容为空
经测试中间的pipe是读到了文件内容的,但是一旦写文件就会为空
即使我把这段程序写成这样:

fs.createReadStream('./template/pc.ftl')
        .pipe(fs.createWriteStream('./template/abc.ftl'));

也都不行,所以应该是fs.createWriteStream的问题,
请问这是为什么呢?


因为你没有错误处理,发生了错误你也感知不到,只能通过结果判断

const readStream = fs.createReadStream(path.join(__dirname, 'xxx_read.ftl'))
const writeStream = fs.createWriteStream(path.join(__dirname, 'xxx_write.ftl'))
readStream.pipe(writeStream)
readStream.on('error', (error) => {
  console.log('readStream error', error.message);
})
writeStream.on('error', (error) => {
  console.log('writeStream error', error.message);
})

监听错误事件, 最好打到日志里面去!!!!仅供参考 希望有帮助


我刚才测试了一下,是因为你的权限不够.所以代码也不会报错。写的文件是0B

在当前目录输入命令:la 
查看文件的权限

输入命令:who am i
查看自己用户角色和组信息

如果是权限的问题就更改node执行时候的权限就行了。


可以试试:

fs.createReadStream('./template/pc.ftl')
.pipe(fs.createWriteStream('./template/abc.ftl'))
.on('error', function(e){
  console.error(e)
})
【热门文章】
【热门文章】