node.js - NodeJS - 如何异步读取多个文件并将读取的内容写入一个文件

标签 node.js asynchronous read-write

我想在 NodeJS 中异步读取多个文件。当读取顺序无关紧要时,最好同时读取多个文件。

但是,我正在尝试将这些文件的内容一起写入一个文件中。我可以很好地写入一个文件,但是在将所有内容写入该文件之前,如何确保所有文件都已被读取?

最佳答案

使用async :

'use strict';

let fs = require('fs'),
    async = require('async'),
    inputs = ['in1', 'in2'],
    output = 'out';

function fuse(inputs, output, callback) {
    async.map(inputs, (path, callback) => {
        fs.readFile(path, callback);
    }, (err, contents) => {
        if(error) {
            callback(error);
        } else {
            fs.writeFile(output, contents.reduce((a, b) => {
                return a + b;
            }), callback);
        }
    });
}

fuse(inputs, output, (error) => {
    if(error) {
        console.log('Error: ' + error);
    } else {
        console.log('OK');
    }
});

编辑:

使用 promise :

'use strict';

const fs = require('fs'),
    inputs = ['in1', 'in2'],
    output = 'out'

// Promisify fs.readFile
function read(file) {
    return new Promise((resolve, reject) => {
        fs.readFile(file, (error, data) => {
            if(error) {
                reject(error);
            } else {
                resolve(data);
            }
        });
    });
}

// Promisify fs.writeFile
function write(file, data) {
    return new Promise((resolve, reject) => {
        fs.writeFile(file, data, (error) => {
            if(error) {
                reject(error);
            } else {
                resolve();
            }
        });
    });
}

Promise.all(inputs.map(read)) // Read all files
    .then((data) => { // data will be a array of the data in the files
        const outData = data.reduce((a, b) => {
            return a + b; // concatenate the data
        })
        return write(output, outData); // write the output
    })
    .then(() => {
        console.log('OK');
    })
    .catch((error) => {
        console.error(error);
    });

(未经测试,但总体思路在这里) 正如 libik 所指出的,fs-promiseutil.promisifybluebird 是 promisify fs.readFile 的替代品和fs.writeFile

关于node.js - NodeJS - 如何异步读取多个文件并将读取的内容写入一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39020704/

相关文章:

node.js - 如何在 Pug 模板文件中使用 i18n 变量?

asynchronous - 未取消 future

linux - Linux 中读取文件

console - MacOS 上的 Flutter 错误文件描述符错误

javascript - 动态地将新链接附加到列表顶部而不是列表底部

node.js - 如何使用node.js创建 session ?

html - 验证密码和用户名nodejs mysql

javascript - MongoDB 查找文档如果存在 - 更新否则 - 插入

javascript - Angular + Requirejs - 以错误的顺序加载

mysql - InnoDB并发读写