我正在使用 node-crontab 来运行脚本。 fs.writeFile 在循环第一次运行时覆盖,但之后是附加数据。我曾尝试在写入之前删除文件,但正在做同样的事情,第一次删除它,但在随后的运行中开始追加。我该怎么办?
这是脚本:我省略了一些环境变量...
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://credentials@api.comettracker.com/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');
});
};
});
};
最佳答案
首先,当我运行您的代码时,如果不存在任何文件,则会收到错误消息。请参阅下面的修复。
为了确保您正在编写,您可以显式地将写入标志提供给选项参数,如下所示:
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');
});
});
顺便说一句,fs.unlink() 并不是真正需要的,因为 fs.writeFile() 会覆盖文件。
关于javascript - fs.writeFile 不覆盖文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33678298/