从fs.createWriteStream创建的文件读取数据时遇到问题。
在读取文件之后,而不是在调用文件时,看起来好像stream.write在程序的末尾执行了(这可以解释为什么在output_variable_3中什么都没有)。>
使用的功能如下(简化):
module.exports = async data1 => {
console.log('start');
try {
const stream = fs.createWriteStream(filename_1, { flags: "a" });
console.log('stream created');
stream.write("some data", (err) => {
if (err) {
console.log(err.message);
} else {
console.log("data written");
}
});
for (const variable_1 of object_1) {
const variable_2 = await function2({
// generates a buffer
});
stream.write(variable_2, (err) => {
if (err) {
console.log(err.message);
} else {
console.log("data written");
}
});
}
stream.end();
console.log('stream ended');
console.log('opening file');
const variable_3 = fs.readFileSync(filename_1);
console.log('file opened and read with data: ' + variable_3);
return;
} catch (error) {
console.log(error);
}
};
Output:
> start
> stream created
> stream ended
> opening file
> file opened and read with data:
> data written
> data written
但是一旦代码运行,当我打开文件名_1(通过资源管理器)时,是否存在全部数据?!
答案 0 :(得分:0)
让它排在最后。
没有意识到流函数不会返回承诺,所以我不得不手动返回承诺。
此处代码已更改:
module.exports = async data1 => {
console.log('start');
try {
const stream = fs.createWriteStream(filename_1, { flags: "a" });
console.log('stream created');
stream.write("some data", (err) => {
if (err) {
console.log(err.message);
} else {
console.log("data written");
}
});
for (const variable_1 of object_1) {
const variable_2 = await function2({
// generates a buffer
});
stream.write(variable_2, (err) => {
if (err) {
console.log(err.message);
} else {
console.log("data written");
}
});
}
stream.end();
console.log('stream ended');
console.log('opening file');
const variable_3 = fs.readFileSync(filename_1);
console.log('file opened and read with data: ' + variable_3);
return new Promise(resolve => {
stream.on('finish', () => {
resolve('done');
console.log("createNRRD is done");
});
});
} catch (error) {
console.log(error);
}
};