gpt4 book ai didi

node.js - 在 NodeJS 中监听 createReadStream 上的 'data' 事件时,写入 createWriteStream 的文件被损坏

转载 作者:太空宇宙 更新时间:2023-11-03 23:01:18 40 4
gpt4 key购买 nike

我有一个 Electron 应用程序,并且我编写了一个使用 Node 的 fs 模块复制文件的服务。当不监听 fs.createReadStreamdata 事件时,文件复制工作正常,但是当我添加 readStream.on('data', ... 事件时,输出文件会损坏(输出文件的大小始终小于原始文件)。这是我复制文件的功能代码:

copyFile(sourcePath: string, targetPath: string): Observable<FileCopyResponseModel> {
const copyResponse = new Subject<FileCopyResponseModel>();
const fileSize = this.node.fs.statSync(sourcePath).size;
const readStream = this.node.fs.createReadStream(sourcePath);
let bytesCopied = 0;

readStream.once("error", (err) => {
const response = new FileCopyResponseModel();
response.is_error = true;
response.error = err;
copyResponse.next(response);
});

readStream.on('data', (buffer) => {
bytesCopied+= buffer.length

const response = new FileCopyResponseModel();
response.is_error = false;
response.is_done = false;
response.size = fileSize;
response.size_copied = bytesCopied;
copyResponse.next(response);
});

this.node.mkdirp(this.node.path.dirname(targetPath), (err) => {
if (err) {
const response = new FileCopyResponseModel();
response.is_error = true;
response.error = err;
copyResponse.next(response);
} else {
const writeStream = this.node.fs.createWriteStream(targetPath);
writeStream.once("error", (err) => {
const response = new FileCopyResponseModel();
response.is_error = true;
response.error = err;
copyResponse.next(response);
});

writeStream.once("close", (ex) => {
const response = new FileCopyResponseModel();
response.is_error = false;
response.is_done = true;
response.size = fileSize;
copyResponse.next(response);
});

readStream.pipe(writeStream);
}
});

return copyResponse;
}

如果我只是注释掉这部分代码,文件就会被正确复制:

readStream.on('data', (buffer) => {
bytesCopied+= buffer.length

const response = new FileCopyResponseModel();
response.is_error = false;
response.is_done = false;
response.size = fileSize;
response.size_copied = bytesCopied;
copyResponse.next(response);
});

知道这里出了什么问题吗?

附注:在监听 data 事件时,可以正确报告复制进度。

最佳答案

我认为您正在尝试使用可读流两次。一旦进入 on('data', 处理程序,一次进入 readStream.pipe(writeStream);on('data', 将在将可读流传输到写入流之前先使用它。

您可以尝试更换该行:

readStream.pipe(writeStream);

readStream.on('data', (buffer) => {
bytesCopied+= buffer.length

const response = new FileCopyResponseModel();
response.is_error = false;
response.is_done = false;
response.size = fileSize;
response.size_copied = bytesCopied;
copyResponse.next(response);
// new bit
writeStream.write(buffer);
});

并从上面的处理程序中删除on('data,

您还可以在读取流结束时结束 writeStream。

readStream.on('end', function() {
console.log('end');
writeStream.end();
});

关于node.js - 在 NodeJS 中监听 createReadStream 上的 'data' 事件时,写入 createWriteStream 的文件被损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47621899/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com