如何在Javascript中写入CSV文件

use*_*183 1 javascript csv jenkins phantomjs

我有一个脚本(使用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();
    });

}
Run Code Online (Sandbox Code Playgroud)

Art*_* B. 5

您可以在附加模式下使用fs模块和write(path, content, mode)方法.

var fs = require('fs');
fs.write(filepath, content, 'a');
Run Code Online (Sandbox Code Playgroud)

filepath文件路径在哪里作为字符串,content是包含CSV行的字符串.

就像是:

address+";"+(new Date()).getTime()+";"+t
Run Code Online (Sandbox Code Playgroud)