javascript - 如何在 Javascript 中写入 CSV 文件

标签 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();
    });

}

最佳答案

您可以使用 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/

相关文章:

jenkins - 如何在没有管道支持的情况下使用 Jenkins 插件?

android - 覆盖 android gradle versionCode 表单命令行

javascript - Nightwatch 集成测试 : Can't select option from select dropdown in Safari

javascript - 代表用户在对讲机上发送消息

c - 从某些字节的文件中读取额外的奇怪字符

python - 如何附加到 CSV 文件?

string - 通过 Perl 从 xls 读取日期到 csv

Jenkins 搜索框结果 URL 不正确

javascript - angularjs - 将 XMLHttpRequest 重构为 $http

javascript - 需要一些类似访客的设计模式