Akash
Akash

Reputation: 324

Cant read from a file and write the same content to another file in nodejs

I am trying to open and read a file names spam0 and I want to get its contents and write them to another file named input.txt, but I am getting an error.

This is what I have tried till now:

file0 = fs.open("./spam0.txt", 'r', function(err, data) // opening spam0 
{
    if (err) {
        console.log("error");
    } else {
        //write spam0 data tp input.txt
        file = fs.writeFile('input.txt',  data, {flag:"w+",encoding:"utf8"} ,function(err, data)
        {
            if (err) {
                throw err;
            }
        });
    }
});

The error I get is:

fs.js:75
throw new TypeError('"options" must be a string or an object, got ' +
^
TypeError: "options" must be a string or an object, got number instead.
at getOptions (fs.js:75:11)
at Object.fs.writeFile (fs.js:1269:13)
at C:\Users\akash\Desktop\riidl\node.trail.js:12:14
at FSReqWrap.oncomplete (fs.js:135:15)

Upvotes: 2

Views: 1837

Answers (1)

sempasha
sempasha

Reputation: 623

In other words you want to copy contents from one file to another, right? It would be much easier to create read stream from origin file and pipe it to write stream of destination file.

const fs = require('fs');
const origin = fs.createReadStream('./spam0.txt', {flags: 'r'});
const destination = fs.createWriteStream('input.txt', {flags: 'w+'});    
origin.pipe(destination);

Of course, if you want to do some transformation, you may use Transform streams (see tutorial by Jeff Barczewski).

const fs = require('fs');
const stream = require('stream');
const origin = fs.createReadStream('./spam0.txt', {
    flags: 'r',
    // read data as a string not as a buffer
    encoding: 'utf8'
});
const transform = new stream.Transform({
    // accept data as a strings
    writableObjectMode: true,
    transform: function removeNewLines(chunk, encoding, callback){
        callback(null, chunk.replace(/\n/g, ''));
    }
});
const destination = fs.createWriteStream('input.txt', {
    flags: 'w+',
    // write data as a strings, this is default value
    encoding: 'utf8'
});

origin.pipe(transform).pipe(destination);

Upvotes: 3

Related Questions