4

In this below code I can read file1.txt data and write it to file2.txt, but I want to read file1, file2, file3, and file4 and then write all those data to file5.txt. How to do that? Can anyone edit the below code as i am beginner

 var fs = require("fs");

    fs.readFile('file1.txt',function(err, data){
        fs.writeFile('file2.txt', data)
    });
Dark Ninja
  • 149
  • 2
  • 13

3 Answers3

3

One method to do this would be to nest the multiple readFiles and then have the writeFile nested inside. Something like this:

var fs = require("fs");

fs.readFile('file1.txt',function(err1, data1){
    fs.readFile('file2.txt',function(err2, data2){
        fs.readFile('file3.txt',function(err3, data3){
             if(err1 || err2 || err3){
                   throw new Error();
             }
             let data = data1+data2+data3;
             fs.writeFile('file4.txt', data);
         });
    });
});

The other method to achieve this would be to use the Bluebird or a similar promise library.

var fs = require('fs');
var Promise = require('bluebird');
var readFile = Promise.promisify(fs.readFile);
var writeFile = Promise.promisify(fs.writeFile);

var promiseArray = [readFile('file1.txt'), readFile('file2.txt'), readFile('file3.txt')];

Promise.all(promiseArray).then((dataArray)=>{
     var data = '';
     for(var i=0;i<dataArray.length;i++){
          data += dataArray[i];
     }
     return writeFile('file4.txt', data);
});

I would suggest to use the second method. Hope this helps :)

dRoyson
  • 1,466
  • 3
  • 14
  • 25
1

The simplest solution I found was installing the package concat -- it will do all the legwork for you :) Please also note that writeFile has been deprecated for writeFileSync (Code [DEP0013]).

First install the package

npm install concat

Then code

const concat = require('concat'); //Or use ES6 Syntax
const fs = require('fs');


concat(['1.txt', '2.txt', '3.txt']).then(files_being_written => 
fs.writeFileSync('your-concated-file.txt', files_being_written))

// or this way
// concat(['1.txt', '2.txt', '3.txt'], 'your-concated-file.txt') 

Source(s):

https://www.npmjs.com/package/concat https://github.com/nodejs/node/issues/14770

Cody
  • 329
  • 4
  • 16
0

I will opt for the promise library for this. Making your Objects thenable increases code readability and prevents the code from growing in the right side. My solution will be almost same like other solution except for I am using nodejs Buffer to concatenate the data of other files.

const fs = require('fs')
const file1 = 'a.txt'
const file2 = 'b.txt'

const allPromises = [file1, file2].map(eachFile => {
    return new Promise((resolve, reject) => {
        fs.readFile(eachFile, (err, data) => {
            if(err) {
                reject(err)
            }else {
                resolve(data)
            }
        })
    })
})

Promise.all(allPromises).then(onfulfilled => {
    const totalBufferContent = Buffer.concat(onfulfilled)
    fs.writeFile('c.txt', totalBufferContent, (err) => {
        if(err) throw err;

        console.log('Done')
    })
})
Parnab Sanyal
  • 749
  • 5
  • 19