简体   繁体   English

使用fs.write而不是fs.writeFile覆盖文件的所有内容

[英]Overwrite all contents of file using fs.write instead of fs.writeFile

Using Node.js, is there a way to overwrite all the file contents with fs.write instead of fs.writeSync? 使用Node.js,有没有办法用fs.write而不是fs.writeSync覆盖所有文件内容? It appears that fs.write will write in the bytes in the position given but leave the other bytes intact? 似乎fs.write会写入给定位置的字节,但保留其他字节不变?

https://nodejs.org/api/fs.html#fs_fs_write_fd_buffer_offset_length_position_callback https://nodejs.org/api/fs.html#fs_fs_write_fd_buffer_offset_length_position_callback

fs.write() writes bytes into the file positions you give it. fs.write()将字节写入您提供的文件位置。 It replaces those bytes in the file. 它替换文件中的那些字节。 It does not affect any other bytes in the file. 它不会影响文件中的任何其他字节。 That's how it works. 这就是它的工作原理。

You can separately use fs.ftruncate() to change the length of an open file descriptor and, if you pass it 0 as the new length, it will truncate the file a zero length file which you could then fs.write() new bytes to. 您可以单独使用fs.ftruncate()来更改打开文件描述符的长度,如果将其作为新长度传递0 ,它将截断文件的零长度文件,然后您可以fs.write()新字节至。

If you use the O_TRUNC flag with fs.open() , then it will truncate any existing file to zero length when you open it and then you can fs.write() into the now empty file. 如果你使用带有fs.open()O_TRUNC标志,那么当你打开它时它会将任何现有文件截断为零长度,然后你可以将fs.write()转换为现在空的文件。

If you just wish to replace the entire contents of a file with one operation, you can use fs.writeFile() instead. 如果您只想用一个操作替换文件的全部内容,则可以使用fs.writeFile()代替。 That will open the file for writing, clearing any previous contents (can modify behavior with options you pass it), write data to the file and then close it. 这将打开文件进行写入,清除以前的任何内容(可以使用您传递的选项修改行为),将数据写入文件然后关闭它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM