简体   繁体   English

在Node.js中覆盖文件

[英]Overwrite a File in Node.js

Im trying to write into a text file in node.js. 我试图写入node.js中的文本文件。 Im doing this the following way: 我这样做的方式如下:

fs.writeFile("persistence\\announce.txt", string, function (err) {
    if (err) {
        return console.log("Error writing file: " + err);
    }
});

whereas string is a variable. 而string是一个变量。

This function will begin it`s writing always at the beginning of a file, so it will overwrite previous content. 此函数将始终在文件的开头写入,因此它将覆盖以前的内容。

I have a problem in the following case: 我在以下情况下遇到问题:

old content: 旧内容:

Hello Stackoverflow

new write: 新写:

Hi Stackoverflow

Now the following content will be in the file: 现在,以下内容将在文件中:

Hi stackoverflowlow

The new write was shorter then the previous content, so part of the old content is still persistent. 新写入比之前的内容短,因此旧内容的一部分仍然是持久的。

My question: 我的问题:

What do I need to do, so that the old content of a file will be completely removed before the new write is made? 我需要做什么,以便在新写入之前完全删除文件的旧内容?

You can try truncating the file first: 您可以先尝试截断文件:

fs.truncate("persistence\\announce.txt", 0, function() {
    fs.writeFile("persistence\\announce.txt", string, function (err) {
        if (err) {
            return console.log("Error writing file: " + err);
        }
    });
});

Rename the old file and append to therefore a non existent file (creating a new one). 重命名旧文件并附加到不存在的文件(创建一个新文件)。 This way you have on the one hand a backup and on other hand a fresh updated file ./config.json : 这样,您一方面可以备份,另一方面可以获得新的更新文件./config.json

fs.renameSync('./config.json', './config.json.bak')
fs.appendFileSync('./config.json', text)

(sync version, might throw) (同步版,可能会抛出)

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

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