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?
fs.createWriteStream(path[,options])
optionsmay also include astartoption to allow writing data at some position past the beginning of the file. Modifying a file rather than replacing it may require aflagsmode ofr+rather than the default modew. The encoding can be any one of those accepted by Buffer.If
autoCloseis set to true (default behavior) on'error'or'finish'the file descriptor will be closed automatically. IfautoCloseis false, then the file descriptor won't be closed, even if there's an error. It is the application's responsibility to close it and make sure there's no file descriptor leak.Like ReadStream, if
fdis specified, WriteStream will ignore thepathargument and will use the specified file descriptor. This means that no'open'event will be emitted.fdshould be blocking; non-blockingfds should be passed to net.Socket.If
optionsis a string, then it specifies the encoding.
After, reading this long article. You should understand how it works.
So, here's an example of createWriteStream().
/* The fs.createWriteStream() returns an (WritableStream {aka} internal.Writeable) and we want the encoding as 'utf'-8 */
/* The WriteableStream has the method write() */
fs.createWriteStream('out.txt', 'utf-8')
.write('hello world');