我有一个脚本(使用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)附加模式下的方法一起使用。
write(path, content, mode)
var fs = require('fs'); fs.write(filepath, content, 'a');
其中filepath,文件路径是字符串,content是包含CSV行的字符串。
filepath
content
就像是:
address+";"+(new Date()).getTime()+";"+t