how to write files in Node.js?

Answer

Currently there are 3 ways to write a file:

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.

A WriteStream, as the name says, is a stream. A stream by definition is “a buffer” containing data which moves in one direction (source ► destination). But a writable stream is not necessarily “buffered”. A stream is “buffered” when you write n times, and at time n+1, the stream sends the buffer to the kernel (because it's full and needs to be flushed).

example:
var fs = require('fs');
fs.writeFile("/tmp/test", "Hey there!", function(err) {
if(err) {
return console.log(err);
}

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

All node.js Questions

Ask your interview questions on node-js

Write Your comment or Questions if you want the answers on node-js from node-js Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---