【发布时间】:2019-06-14 05:27:01
【问题描述】:
我是 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);
}
【问题讨论】:
-
你到底要达到什么目标?你想用 async/await 语法写这个函数吗?或者你想改变功能?
-
对于您的项目,我建议您使用 Promises。 This 可能符合您的要求。
-
async/await不能让事情同步运行。无论如何,忘记让你的函数同步的想法;而是坚持使用异步模式(可能涉及async/await)。 -
@MohammadGanji 我想写一个递归加密文件的函数,在加密过程完成后执行另一个函数。
标签: javascript node.js asynchronous synchronous