0

How can I append data to a file using node.js

I already have a file named myfile.json with data. I want to check if the file name exists and then append some data to that file.

I'm using following code

var writeTempFile = function (reportPath, data, callback) {   
    fs.writeFile(reportPath, data, function (err) {
        //if (err) //say(err);
        callback(err);
    });
}
writeTempFile(reportDir + '_' + query.jobid + ".json", data, function (err) {
    context.sendResponse(data, 200, {
        'Content-Type': 'text/html'
    });
3
  • There is one issue: You can't truly append data to a file of JSON format while preserving the format. You would have to read the data, parse it as JSON, edit the JSON and add your data, and then write the JSON back to the file. Commented Jan 23, 2014 at 5:12
  • How can it is possible in code wise? Commented Jan 23, 2014 at 5:55
  • It really depends on your JSON structure and what data you are trying to append. Commented Jan 23, 2014 at 6:34

3 Answers 3

1

You can use jsonfile

var jf = require('jsonfile');
var yourdata;
var file = '/tmp/data.json';
jf.readFile(file, function(err, obj) {
    if(!err) {
        var finalData = merge(obj, yourdata);

        jf.writeFile(file, finalData, function(err) {
            console.log(err);
        });
    }
});

You need to implement your merging logic in merge(object1, object2)

https://npmjs.org/package/jsonfile

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

Comments

0

Check out the following code.

function addToFile(reportPath, data, callback){
    fs.appendFile(reportPath, data, function (err) {
        callback(err);
    });
}

1 Comment

iam getting this error` fs.appendFile(reportPath, data, function (err) ^ TypeError: Object #<Object> has no method 'appendFile' `
0

Node offers fs module to work with file system. To use this module do

var fs = require('fs')

To append some data to file you can do:

fs.appendFile('message.txt', 'data to append', function (err) {
  if (err) throw err;
 console.log('The "data to append" was appended to file!');
});

Node offers you both synchronous and asynchronous method to append data to file, For more information please refer to this documentation

5 Comments

am getting TypeError: Object #<Object> has no method 'appendFile'
@Sush you might be using an old version of Node.js if you are getting that error.
my node version is v0.6.12
Purely a guess, but I think a lot of the fs stuff changed around 0.9ish. Prior to that it has a lot of cross-platform issues (not to say that it's void of them now). It's on v0.10.24 now.
@Sush use nvm to upgrade it to the latest. It should be working after that.

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.