Node.js异步到同步

时间:2019-01-20 18:21:33

标签: javascript node.js asynchronous synchronous

我是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);
}

2 个答案:

答案 0 :(得分:2)

尝试使用Promise。通过略微更改代码,您可以使功能充分发挥作用,然后等待所有承诺解决或拒绝,然后再采取行动。

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);

我尚未运行此代码,因此可能需要进行一些调整才能使其正常工作,但这是一般要点。

答案 1 :(得分:0)

您不必同步加密文件,也可以异步进行加密。要遍历目录并获取其文件,请递归使用fs.readdir直到找不到更多文件,然后可以对找到的每个文件运行encrypt