fs.writefile(node)添加了已经存在的文件,而不是替换此信息

发布于 2025-02-02 02:00:20 字数 356 浏览 3 评论 0原文

我制作了一个代码来使用FS和Node-Cron编写文件,以每X分钟运行此文件。我第一次获取数据,但是在下一项工作中,我也会在文件中再次添加数据,我也想创建一个新文件并替换旧文件(和以前的信息),但我仍然有这个附加而不是新数据,

fs.writeFile(path.join(__dirname, '_data', 'data.json'), JSON.stringify(data, this, 2), {flag: 'w'}, err => {
    if (err) {
        console.error(err);
    } else {
        console.log("Success");
    }
});

I made a code to write a file using fs and node-cron to run this every x minutes. I get the data the first time, but in the next job I get the data added again in the file and the old one too, I wan to create a new file and replace the old one (and the previous information) but I still have this appended instead of only the new data,

fs.writeFile(path.join(__dirname, '_data', 'data.json'), JSON.stringify(data, this, 2), {flag: 'w'}, err => {
    if (err) {
        console.error(err);
    } else {
        console.log("Success");
    }
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

哭了丶谁疼 2025-02-09 02:00:20

我能够理解我的错误,我应该再次初始化变量数据,以清除先前的结果。

    //Save data into fs
    fs.writeFile(path.join(__dirname, '_data', 'varlix.json'), JSON.stringify(varlix, this, 2), err => {
        if (err) {
            console.error(err);
        } else {
            console.log("Success");
        }
    });
    data = [];

I was able to understand my error, I should initialize again variable data in order to clear previous results.

    //Save data into fs
    fs.writeFile(path.join(__dirname, '_data', 'varlix.json'), JSON.stringify(varlix, this, 2), err => {
        if (err) {
            console.error(err);
        } else {
            console.log("Success");
        }
    });
    data = [];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文