Node.js / 删除文件中的内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17371224/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:54:56  来源:igfitidea点击:

Node.js / Delete content in file

node.js

提问by user937284

I want to delete the content of a simple text file with node.js. Or replace the file with a new/empty one.

我想用 node.js 删除一个简单文本文件的内容。或者用新的/空的文件替换文件。

How can I achieve this in node?

如何在节点中实现这一点?

回答by Andbdrew

You are looking for fs.truncateor fs.writeFile

您正在寻找fs.truncatefs.writeFile

Either of the following will work:

以下任一方法都有效:

const fs = require('fs')
fs.truncate('/path/to/file', 0, function(){console.log('done')})

or

或者

const fs = require('fs')
fs.writeFile('/path/to/file', '', function(){console.log('done')})

There are also synchronous versionsof both functionsthat you should not use.

也有同步版本两种功能,你不应该使用。

回答by Peter Lyons

fs.unlinkis the call you need to delete a file. To replace it with different contents, just overwrite it with fs.writeFile.

fs.unlink是删除文件所需的调用。要用不同的内容替换它,只需用fs.writeFile.