0

How can you append text to an existing file during periodicactivity in Node.js? My goal is to log successive sensor values into a textfile.

I am able to create a file and write a single value to it during periodic activity, but each time I append that file the old data is erased (or perhaps a new file is created altogether). Any data that was in the file prior to periodicactivity() is also lost.

fs.open('SensorData.txt', 'w', function(err, data) {
if (err) {
    console.log("ERROR !! " + err);
} else {
    fs.appendFile('SensorData.txt', content, function(err) {
        if (err)
            console.log("ERROR !! " + err);
        fs.close(data, function() {
            console.log('written success');
        })
    });
}

I found the above code on stack exchange, but I am unable to make it function in this context. I'm new to Node.js and I'm sure there is a better way to accomplish my task. I would greatly appreciate any input.

Thank you jfriend00!

Jsaunders
  • 3
  • 2

1 Answers1

1

You can just use fs.appendFile() which handles it all for you:

fs.appendFile('SensorData.txt', content, function(err) {
    if (err) {
        console.log("error appending data to SensorData.txt");
    } else {
        // data appended successfully
    }
});

You don't need to open or close the file when using fs.appendFile() as it does all that for you in the one call. It will open the file for appending and then write the content to the end of the file and then close the file.


In your original code the line of code fs.open('SensorData.txt', 'w', ...) would recreate the file from scratch each time, thus wiping out all previous content. Since fs.appendFile() manages the opening and closing of the file for you automatically, there is no need to open the file yourself. If you wanted to open a file for appending to it, you would use fs.open('SensorData.txt', 'a', ...), but that is not necessary for your current task.

jfriend00
  • 683,504
  • 96
  • 985
  • 979