如何在 Node js 中正确关闭可写流?
How to properly close a writable stream in Node js?
我对 javascript 还很陌生。我正在使用节点 js 可写流来编写 .txt 文件;它运行良好,但我无法理解如何正确关闭文件,因为只要程序是 运行,它的内容就是空白的。更详细地说,我需要在写入该 .txt 文件后读取它,但这样做 returns 一个空缓冲区。
let myWriteStream = fs.createWriteStream("./filepath.txt");
myWriteStream.write(stringBuffer + "\n");
myWriteStream.on('close', () => {
console.log('close event emitted');
});
myWriteStream.end();
// do things..
let data = fs.readFileSync("./filepath.txt").toString().split("\n");
好像是.end()
方法发出的事件是在文件读取后触发的,导致读取为空。如果我放一个 while()
来等待事件被触发,这样我就可以确定流在读取之前关闭,程序将永远等待。
你知道我做错了什么吗?
你遗漏了 2 件事,一个测试成功了
那么你需要等待流完成事件
const { readFileSync, createWriteStream } = require('fs')
const stringBuffer = Buffer.from(readFileSync('index.js')
)
const filePath = "./filepath.txt"
const myWriteStream = createWriteStream(filePath)
let backPressureTest = false;
while (!backPressureTest) {
backPressureTest = myWriteStream.write(stringBuffer + "\n");
}
myWriteStream.on('close', () => {
console.log('close event emitted');
});
myWriteStream.on('finish', () => {
console.log('finish event emitted');
let data = readFileSync(filePath).toString().split("\n");
console.log(data);
});
myWriteStream.end();
我对 javascript 还很陌生。我正在使用节点 js 可写流来编写 .txt 文件;它运行良好,但我无法理解如何正确关闭文件,因为只要程序是 运行,它的内容就是空白的。更详细地说,我需要在写入该 .txt 文件后读取它,但这样做 returns 一个空缓冲区。
let myWriteStream = fs.createWriteStream("./filepath.txt");
myWriteStream.write(stringBuffer + "\n");
myWriteStream.on('close', () => {
console.log('close event emitted');
});
myWriteStream.end();
// do things..
let data = fs.readFileSync("./filepath.txt").toString().split("\n");
好像是.end()
方法发出的事件是在文件读取后触发的,导致读取为空。如果我放一个 while()
来等待事件被触发,这样我就可以确定流在读取之前关闭,程序将永远等待。
你知道我做错了什么吗?
你遗漏了 2 件事,一个测试成功了 那么你需要等待流完成事件
const { readFileSync, createWriteStream } = require('fs')
const stringBuffer = Buffer.from(readFileSync('index.js')
)
const filePath = "./filepath.txt"
const myWriteStream = createWriteStream(filePath)
let backPressureTest = false;
while (!backPressureTest) {
backPressureTest = myWriteStream.write(stringBuffer + "\n");
}
myWriteStream.on('close', () => {
console.log('close event emitted');
});
myWriteStream.on('finish', () => {
console.log('finish event emitted');
let data = readFileSync(filePath).toString().split("\n");
console.log(data);
});
myWriteStream.end();