admin管理员组文章数量:1135190
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?
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?
Share Improve this question edited May 10, 2017 at 12:50 mihai 38.5k11 gold badges62 silver badges89 bronze badges asked May 10, 2017 at 12:25 Tomas KatzTomas Katz 1,8143 gold badges14 silver badges29 bronze badges 2 |3 Answers
Reset to default 181fs.writeFileSync
and fs.writeFile
overwrite 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.writeFile
Asynchronously writes data to a file, replacing the file if it already exists.
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(path,content,{encoding:'utf8',flag:'w'})
When you say "best way", i think at performance and scalability and i'd say use the asynchronous method
fs.writeFileSync(path,string)
as the name suggest is synchronous (blocking api) the thread is held for the whole lifecycle of the request, that means your nodejs thread will be blocked until the operation finishes and this behavior in a production environment with simultaneous connections from multiple clients could kill your app.
Do not think at the single line of code, less code doesn't mean better performance.
本文标签: javascriptWhat39s the best way to overwrite a file using fs in nodejsStack Overflow
版权声明:本文标题:javascript - What's the best way to overwrite a file using fs in node.js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736920883a1956456.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
fs.writeFileSync(path, string, { flag: fs.constants.O_TRUNC | fs.constants.O_WRONLY })
– xuxu Commented Aug 9, 2022 at 7:43