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

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks it helped me and another think how to create file1,file2,file3 with text in nest like this
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

Comments

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')
    })
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.