在Node.js中覆盖文件 [英] Overwrite a File in Node.js

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

问题描述

我试图写入node.js中的文本文件。
我这样做的方式如下:

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);
    }
});

而string是一个变量。

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:

旧内容:

Hello Stackoverflow

new write:

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.

我的问题:

我需要做什么,以便在以前完全删除文件的旧内容新写入?

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);
        }
    });
});

这篇关于在Node.js中覆盖文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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