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])
options
may also include astart
option to allow writing data at some position past the beginning of the file. Modifying a file rather than replacing it may require aflags
mode ofr+
rather than the default modew
. The encoding can be any one of those accepted by Buffer.If
autoClose
is set to true (default behavior) on'error'
or'finish'
the file descriptor will be closed automatically. IfautoClose
is 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
fd
is specified, WriteStream will ignore thepath
argument and will use the specified file descriptor. This means that no'open'
event will be emitted.fd
should be blocking; non-blockingfd
s should be passed to net.Socket.If
options
is 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');