javascript - nodejs异步到同步
问题描述
我是 nodejs 和 javascript 的新手,我目前正在开发一个开源项目,因为昨晚我试图将此函数从异步转换为同步,但我做不到,我使用了 async / await 但我认为我不太了解这个概念,这个函数使用 aes256 算法加密和压缩文件,我异步工作得很好,但我想添加这个新功能,允许您递归加密目录的内容。
function encrypt({ file, password }, error_callback, succ_callback) {
const initVect = crypto.randomBytes(16);
// Generate a cipher key from the password.
const CIPHER_KEY = crypto.createHash('sha256').update(password).digest();;
const readStream = fs.createReadStream(file);
const gzip = zlib.createGzip();
const cipher = crypto.createCipheriv('aes-256-cbc', CIPHER_KEY, initVect);
const appendInitVect = new AppendInitVect(initVect);
// Create a write stream with a different file extension.
const writeStream = fs.createWriteStream(path.join(file + ".dnc"));
readStream
.pipe(gzip)
.pipe(cipher)
.pipe(appendInitVect)
.pipe(writeStream);
readStream.on('error', error_callback);
readStream.on('end', succ_callback);
}
解决方案
尝试使用承诺。通过稍微更改代码,您可以对函数进行承诺,然后等待所有承诺解决或拒绝,然后再采取行动。
function encrypt({ file, password }) {
const initVect = crypto.randomBytes(16);
// Generate a cipher key from the password.
const CIPHER_KEY = crypto.createHash('sha256').update(password).digest();;
const readStream = fs.createReadStream(file);
const gzip = zlib.createGzip();
const cipher = crypto.createCipheriv('aes-256-cbc', CIPHER_KEY, initVect);
const appendInitVect = new AppendInitVect(initVect);
// Create a write stream with a different file extension.
const writeStream = fs.createWriteStream(path.join(file + ".dnc"));
readStream
.pipe(gzip)
.pipe(cipher)
.pipe(appendInitVect)
.pipe(writeStream);
const promise = new Promise();
writeStream.on('error', err => promise.reject(err));
writeStream.on('end', data => promise.resolve(data));
return promise;
}
const promise1 = encrypt({file1, password1});
const promise2 = encrypt({file2, password2});
Promise.all([promise1, promise2])
.then(succ_callback)
.catch(error_callback);
我没有运行此代码,因此可能需要进行一些调整才能使其正常工作,但这是一般要点。
推荐阅读
- c++ - 优化特征表达
- python - 如何将泡菜文件加载到numpy数组
- mongodb - 在 devextreme 中关联图表和表格
- android - SciChart TradeChartAxisLabelProvider 自定义格式以显示天、月
- google-chrome-app - 使用清单部署 G Suite Marketplace 应用。(G Drive UI 集成)
- python - 在图例中使用线和点标记为两个绘图共享相同的标签
- python-3.x - 如何使用 Pyshark 提取数据包的有效负载
- c# - 如何访问 DataGrid RowHeaderTemplate 或 DataGrid.RowHeaderSyle 中定义的元素
- vue.js - Vue - 从回调将数组推入嵌套数组
- python - 在 CV 期间使用 GridSearchCV 在内部缩放训练数据以进行超参数优化