使用node.js中的fs覆盖文件的最佳方法是什么 [英] What's the best way to overwrite a file using fs in node.js

查看:952
本文介绍了使用node.js中的fs覆盖文件的最佳方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试覆盖现有文件。
我首先检查文件是否存在使用:

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) 

问题是文件已经存在,我想重写其所有内容。
是否有单行解决方案,到目前为止我搜索并找到了使用
fs.truncate& amp; fs.write,但是有没有一个命中解决方案?

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.writeFileSync fs.writeFile 默认情况下覆盖该文件,如果您想要这样做,则无需额外检查。这在文档中提到:

fs.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.

这篇关于使用node.js中的fs覆盖文件的最佳方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆