Writing files in Node.js

前端 未结 19 2356
情歌与酒
情歌与酒 2020-11-21 11:57

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?

19条回答
  •  醉梦人生
    2020-11-21 12:21

    fs.createWriteStream(path[,options])

    options may also include a start option to allow writing data at some position past the beginning of the file. Modifying a file rather than replacing it may require a flags mode of r+ rather than the default mode w. 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. If autoClose 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 the path argument and will use the specified file descriptor. This means that no 'open' event will be emitted. fd should be blocking; non-blocking fds 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');
    

提交回复
热议问题