Javascript 在 node.js 中使用 fs 覆盖文件的最佳方法是什么
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43892482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the best way to overwrite a file using fs in node.js
提问by Tomas Katz
I'm trying to overwrite an existing file. I'm first checking if the file exists using:
我正在尝试覆盖现有文件。我首先使用以下方法检查文件是否存在:
fs.existsSync(path)
If file does not exit I'm creating and writing using:
如果文件没有退出,我正在使用以下方法创建和编写:
fs.writeFileSync(path,string)
The problem is when the file already exists and I want to over write all its contents. Is there a single line solution, so far I searched and found solutions that use fs.truncate & fs.write, but is there a one hit solution?
问题是当文件已经存在并且我想覆盖其所有内容时。是否有单行解决方案,到目前为止我搜索并找到了使用 fs.truncate & fs.write 的解决方案,但是否有一个解决方案?
回答by mihai
fs.writeFileSyncand fs.writeFileoverwrite the file by default, there is no need for extra checks if this is what you want to do. This is mentioned in the docs:
fs.writeFileSync并fs.writeFile默认覆盖文件,如果这是您想要做的,则无需额外检查。这在文档中提到:
Asynchronously writes data to a file, replacing the file if it already exists.
将数据异步写入文件,如果文件已存在则替换该文件。
回答by Tomas Katz
Found the solution. fs.writeFileSync gets a third arguments for options that can be an object. So if you get the "File already exist" you should do.
找到了解决办法。fs.writeFileSync 获取可以是对象的选项的第三个参数。所以如果你得到“文件已经存在”,你应该这样做。
fs.writeFileSync(path,content,{encoding:'utf8',flag:'w'})
回答by Karim
when you say best way, i think at performance and scalability and i'd say use the asynchronous methods. for example this
当你说最好的方式时,我认为是性能和可伸缩性,我会说使用异步方法。例如 这个
fs.writeFileSync(path,string)is synchronous, that means your nodejs thread will be blocked until the operation will finish and this in a production environment with simultaneous connections from multiple clients could kill your app.
fs.writeFileSync(path,string)是同步的,这意味着您的 nodejs 线程将被阻塞,直到操作完成,这在具有多个客户端同时连接的生产环境中可能会杀死您的应用程序。
Do not think at the single line of code, less code doesn't mean better performance.
不要在单行代码上思考,更少的代码并不意味着更好的性能。

