我有一个脚本(使用 PhantomJS)来测试加载网页需要多长时间。我想弄清楚的是如何将加载页面所用时间的结果写入 .csv 文件。然后,如果我再次重新运行测试以将另一个结果添加到 .csv 文件。
代码:
var page = require('webpage').create(),
system = require('system'),
t, address;
var pageLoadArray = [];
var csvContents = "";
fs = require('fs');
if (system.args.length === 1) {
console.log('Usage: loadspeed.js <some URL>');
phantom.exit(1);
} else {
t = Date.now();
address = system.args[1];
page.open(address, function (status) {
if (status !== 'success') {
console.log('FAIL to load the address');
}
else {
t = Date.now() - t;
console.log('Page title is ' + page.evaluate(function () {
return document.title;
}));
if(t>7000){
console.log('Loading time was too long... ' + t + "msec");
pageLoadArray.push(t);
console.log(pageLoadArray.length);
console.log(pageLoadArray[0]);
//store the time value to the .csv file
phantom.exit(1);
}
else{
console.log('Loading time ' + t + ' msec');
pageLoadArray.push(t);
console.log(pageLoadArray.length);
console.log(pageLoadArray[0]);
//store the time value to the .csv file
}
}
phantom.exit();
});
}
最佳答案
您可以使用 fs在追加模式下使用 write(path, content, mode)
方法的模块。
var fs = require('fs');
fs.write(filepath, content, 'a');
filepath
是字符串形式的文件路径,content
是包含 CSV 行的字符串。
类似于:
address+";"+(new Date()).getTime()+";"+t
关于javascript - 如何在 Javascript 中写入 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24915609/