我最初在异步函数中使用流的尝试是:
const fs = require('fs');
const openpgp = require('openpgp');
const util = require('util');
const readFileAsync = util.promisify(require('fs').readFile);
const encryptFile = async (inputFile, outputFile) => {
const readableStream = fs.createReadStream(inputFile);
const writeStream = fs.createWriteStream(outputFile);
const pubKey = await readFileAsync('./public.asc');
const options = {
message: openpgp.message.fromBinary(readableStream),
publicKeys: (await openpgp.key.readArmored(pubKey)).keys,
armor: false,
};
const ciphertext = await openpgp.encrypt(options);
const encrypted = ciphertext.message.packets.write();
const stream = await openpgp.stream.webToNode(encrypted);
return new Promise((resolve, reject) => {
readableStream.once('error', reject) // does not call reject if inputFile doesn't exist
stream.once('error', reject);
writeStream.once('finish', resolve);
writeStream.once('error', reject);
stream.pipe(writeStream);
});
};
但是,我发现如果inputFile
是一个不存在的文件的路径,则readableStream
会发出readableStream.once('error', reject)
未处理的错误。 为什么会这样?
所以我也尝试将其包装在Promise中,发现我必须完全删除async / await语法,因此我最终完成了此操作。
这似乎可行,但是由于使用流对我来说是陌生的领域,有人可以指出我错过的任何内容吗,以及是否有编写这种类型代码的更好方法?
const encryptFile = (inputFile, outputFile) => new Promise((resolve, reject) => {
const readableStream = fs.createReadStream(inputFile);
const writeStream = fs.createWriteStream(outputFile);
readableStream.once('error', reject);
writeStream.once('error', reject);
writeStream.once('finish', resolve);
readFileAsync('./public.asc')
.then(openpgp.key.readArmored)
.then((pubKey) => openpgp.encrypt({
message: openpgp.message.fromBinary(readableStream),
publicKeys: pubKey.keys,
armor: false,
})
)
.then((encrypted) => encrypted.message.packets.write())
.then(openpgp.stream.webToNode)
.then((cipherNodeStream) => {
cipherNodeStream.once('error', reject);
cipherNodeStream.pipe(writeStream)
})
.catch(reject);
});