最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Overwrite a File in Node.js - Stack Overflow

programmeradmin1浏览0评论

Im trying to write into a text file in 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.

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?

Im trying to write into a text file in 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.

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?

Share Improve this question asked Feb 3, 2016 at 13:50 Jakob NielsenJakob Nielsen 5,19818 gold badges59 silver badges97 bronze badges 1
  • take a look at the official documentation, you will find something for sure, writeStream or somehting like that or some kind of option. nodejs.org/api – Vitaliy Terziev Commented Feb 3, 2016 at 14:05
Add a comment  | 

2 Answers 2

Reset to default 14

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:

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

(sync version, might throw)

发布评论

评论列表(0)

  1. 暂无评论