node.js - 如何在多个管道写入流中正确使用 Promise
问题描述
var promisePipe = require("promisepipe");
var fs = require("fs");
var crypt = require("crypto");
var // ....
files = ['/mnt/Storage/test.txt', '/mnt/Storage/test2.txt', '/mnt/Storage/test3.txt']
var promises = files.map(function(file_enc) {
return new Promise(function(resolve, reject) {
var file_out = file_enc + '.locked';
promisePipe(
fs.createReadStream(file_enc),
crypt.createCipheriv(alg, genhashsub, iv),
fs.createWriteStream(file_out),
).then(function(streams){
console.log('File written: ' + file_out);
// Promise.resolve(file_out); // tried but doesnt seem to do anything
}, function(err) {
if(err.message.substring(0, 7) === 'EACCES:') {
console.log('Error (file ' + file_out + '): Insufficient rights on file or folder');
} else {
console.log('Error (file ' + file_out + '): ' + err);
}
// Promise.reject(new Error(err)); // tried but doesnt seem to do anything
});
})
});
Promise.all(promises).then(final_function(argument));
我正在尝试加密包含在名为files
.
为了简单起见,我在此示例中手动添加了它们。
我想要发生的事情:
- 创建
promises
数组以promises.all
在完成时调用 - 遍历数组
- 为这个 IO 操作创建 Promise
- 读取文件\
- 加密文件——由于文件大(+3GB),全部使用流完成
- 写文件/
- 完成写入后,解决此 IO 操作的承诺
- 一旦所有承诺都解决(或拒绝),运行完成脚本
怎么了:
- 第一个文件的加密开始
.then(final_function(argument))
叫做- 第一个文件的加密结束
这些文件都被正确加密,之后可以解密。
此外,还会显示错误以及写入确认。
我搜索了 Stack 和 Google,发现了一些类似的问题(有答案)。但它们无济于事,因为许多已经过时。它们工作,直到我将它们重写为承诺,然后我回到我开始的地方。
我还可以使用 8 种不同的方式来完成这项工作,使用 npm 模块或 vanilla 代码,但它们都以一种或另一种方式失败。
解决方案
如果您已经有一个可以使用的承诺(并且promisepipe
似乎创建了一个承诺),那么您通常不应该使用new Promise()
. 看起来你的主要问题是你正在创建你永远不会解决的承诺。
另一个问题是您final_function
在最后一行调用而不是传递将调用final_function
.
我建议尝试一下:
var promises = files.map(function(file_enc) {
var file_out = file_enc + '.locked';
return promisePipe(
fs.createReadStream(file_enc),
crypt.createCipheriv(alg, genhashsub, iv),
fs.createWriteStream(file_out),
).then(function(streams){
console.log('File written: ' + file_out);
return file_out;
}, function(err) {
if(err.message.substring(0, 7) === 'EACCES:') {
console.log('Error (file ' + file_out + '): Insufficient rights on file or folder');
} else {
console.log('Error (file ' + file_out + '): ' + err);
}
throw new Error(err);
});
});
Promise.all(promises).then(() => final_function(argument));
推荐阅读
- botframework - endOfConversation 不是函数
- reactjs - 如何在反应中正确优化事件处理程序
- python - 如何在 Python 中编写 ffmpeg 命令“-ss”
- android - 在 Xamarin 中出现“您需要在此活动中使用 Theme.AppCompat 主题(或后代)”错误
- xcode - Xcode 11 供应配置文件未能通过资格认证
- javascript - 显示 N 项,共 N 项
- javascript - Angular ngrx:TypeError:无法使用元素冻结数组缓冲区视图
- ubuntu - VS Code:错误:EEXIST:文件已存在,mkdir
- google-app-engine - 使用 Identity Aware Proxy,是否可以向同一 GCP 项目中具有不同主机名的另一个 GAE“服务”发出跨源请求?
- postgresql - 连接同一个表的两列的内容产生一个带双引号的名称