ylliX - Online Advertising Network

Quick tip: writing files in node.js

The quick and dirty way is:

var fs = require('fs');
fs.writeFile("/tmp/test", "Hey there!", function(err) {
    if(err) {
        console.log(err);
    } else {
        console.log("The file was saved!");
    }
});

but of course you can use also:

fs.write(fd, buffer, offset, length, position, [callback])

You need to wait for the callback to ensure that the buffer is written to disk. It’s not buffered.

fs.writeFile(filename, data, [encoding], [callback])

All data must be stored at the same time; you cannot perform sequential writes.

fs.createWriteStream(path, [options])

Creates a WriteStream, which is convenient because you don’t need to wait for a callback. But again, it’s not buffered.

Leave a Reply