javascript fs.writeFile 不覆盖文件

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

fs.writeFile not overwriting file

javascriptnode.jswritefile

提问by Vanessa Torres

I am using node-crontab to run the script. fs.writeFile overwrite first time the loop runs but after that is appending data. I have tried deleting the file before writing but is doing the same, deletes it the first time but in the subsequent runs start to append. What should I do?

我正在使用 node-crontab 来运行脚本。fs.writeFile 第一次循环运行时覆盖,但之后是附加数据。我曾尝试在写入之前删除文件,但正在做同样的事情,第一次删除它,但在随后的运行中开始追加。我该怎么办?

This is the script: I ommited some environment variables...

这是脚本:我省略了一些环境变量...

var jobId = crontab.scheduleJob('* * * * *', function() {
//Gettting  system date and adding leading zeros when are single digits.  I need this to build the get request with date filters.

    var d = new Date();
    var nday = d.getDate();
    var nmonth = d.getMonth();
    var nhour = d.getHours();
    var nmin = d.getMinutes();

    var nfullyear = d.getFullYear();
    if (nday < 10) {
        nday = '0' + nday;
    };
    var nmin = nmin - 1;
    if (nmin < 10) {
        nmin = '0' + nmin;
    };
    if (nhour < 10) {
        nhour = '0' + nhour;
    };

    var nmonth = nmonth + 1;
    if (nmonth < 10) {
        nmonth = '0' + nmonth;
    };

    var options = {
        url: 'https://[email protected]/v1/gpsdata' + '?fromdate=' + nfullyear + '-' + nmonth + '-' + nday + 'T' + nhour + '%3a' + nmin + '%3a' + '00',
        method: 'GET',
        rejectUnauthorized: !debug
    };


// HTTP get request
      request(options, function(error, response, body) {
        if (error) throw new Error(error);
        var result = JSON.parse(body)['gps-recs'];

        console.log(result.length);

        //create .csv file 
        buildCSV(result);

    });
});

function buildCSV(result) {


    //adding headers
    csvFile = csvFile.concat('UserNumber' + ',' + 'UserTimeTag' + ',' + 'Latitude' + ',' + 'Longitude' + ',' + 'SpeedMph' + ',' + 'Heading' + ',' + 'Status' + '\r\n');
    // loop runs result.length times
    for (var i = 0; i < result.length; i++) {
        csvFile = csvFile.concat(result[i].UserInfo.UserNumber + ',' + result[i].UserTimeTag + ',' + result[i].Latitude + ',' + result[i].Longitude + ',' + result[i].SpeedMph + ',' + result[i].Heading + ',' + result[i].Status + '\r\n');

    };
    //delete file.csv first
    console.log('before unlink: ');
    fs.unlink('file.csv', function(err){
        if (err) throw err; 
        else {
            console.log('file deleted'); 
            console.log(csvFile);
            fs.writeFile('file.csv', csvFile, function(err) {

            if (err) throw err;
            console.log('file saved');

            });
        };

    });
};

回答by chriskelly

For one thing when I run your code I get an error if no file exists in the first place. See fix below.

一方面,当我运行您的代码时,如果首先不存在文件,我会收到错误消息。请参阅下面的修复。

To be sure you are writing you could can explicitly supply the write flag to the options parameter like so:

为了确保您正在编写,您可以像这样显式地为 options 参数提供写入标志:

console.log('before unlink: ');
fs.unlink('file.csv', function(err){

    // Ignore error if no file already exists
    if (err && err.code !== 'ENOENT')
        throw err;

    var options = { flag : 'w' };
    fs.writeFile('file.csv', csvFile, options, function(err) {
        if (err) throw err;
        console.log('file saved');
    });
});

Btw, fs.unlink() is not really needed since fs.writeFile() overwrites the file.

顺便说一句, fs.unlink() 并不是真正需要的,因为 fs.writeFile() 会覆盖文件。