nodejs:在for循环中写入多个文件

use*_*574 4 node.js

我还在学习nodejs。这个问题与其他一些问题有关(例如,在 Nodejs 中编写多个文件循环)但有点不同。其实很简单。我想写一些文件,完成后继续其他任务。

没有for循环,我是这样做的,

fs.readFile(f1.path, function(err, data) {
    fs.writeFile("/tmp/" + f1.path, data, function(err) {
        fs.readFile(f2.path, function(err, data) {
            fs.writeFile("/tmp/" + f2.path, data, function(err) {
                ...
                if (err) throw err;

                // do something when all files are written
Run Code Online (Sandbox Code Playgroud)

如果我想使用 for 循环转换它,该怎么做?假设我可以将 f1, f2 ... 放入一个数组中并迭代它们。

感谢您的帮助。

Bre*_*tty 5

您可以将承诺保存在一个数组中并用于Promise.all等待它们全部完成:

const fs = require('fs');
const path = require('path');

const files = [f1, f2, ...];

function copyFile(source, destination) {
    const input = fs.createReadStream(source);
    const output = fs.createWriteStream(destination);
    return new Promise((resolve, reject) => {

        output.on('error', reject);
        input.on('error', reject);
        input.on('end', resolve);
        input.pipe(output);
    });
}

const promises = files.map(file => {
    const source = file.path;
    const destination = path.join('/tmp', file.path);
    // Use these instead of line above if you have files in different
    // directories and want them all at the same level:
    // const filename = path.parse(file.path).base;
    // const destination = path.join('/tmp', filename);
    return copyFile(source, destination);
});

Promise.all(promises).then(_ => {
    // do what you want
    console.log('done');
}).catch(err => {
    // handle I/O error
    console.error(err);
});
Run Code Online (Sandbox Code Playgroud)