Writing files in Node.js

  1. Home
  2. javascript
  3. Writing files in Node.js

I’ve been trying to find a way to write to a file when using Node.js, but with no success. How can I do that?

First answer

There are a lot of details in the File System API. The most common way is:

const fs = require('fs');

fs.writeFile("/tmp/test", "Hey there!", function(err) {

    if(err) {
        return console.log(err);
    }

    console.log("The file was saved!");
}); 

Second answer

You can of course make it a little more advanced. Non-blocking, writing bits and pieces, not writing the whole file at once:

var fs = require('fs');
var stream = fs.createWriteStream("my_file.txt");
stream.once('open', function(fd) {
  stream.write("My first row\n");
  stream.write("My second row\n");
  stream.end();
});

Third answer

var path = 'public/uploads/file.txt',
buffer = new Buffer("some content\n");

fs.open(path, 'w', function(err, fd) {
    if (err) {
        throw 'error opening file: ' + err;
    }

    fs.write(fd, buffer, 0, buffer.length, null, function(err) {
        if (err) throw 'error writing file: ' + err;
        fs.close(fd, function() {
            console.log('file written');
        })
    });
});
Reprint:https://stackoverflow.com/questions/2496710/writing-files-in-node-js
Spread the love

Related articles

Comments are closed.