如何在 Javascript 中写入 CSV 文件 [英] How to write to CSV file in Javascript

查看:24
本文介绍了如何在 Javascript 中写入 CSV 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本(使用 PhantomJS)来测试加载网页需要多长时间.我想弄清楚的是如何将页面加载时间的结果写入 .csv 文件.然后,如果我要再次重新运行测试以将另一个结果添加到 .csv 文件中.

I have a script (using PhantomJS) that tests how long it takes to load a webpage. What I am trying to figure out is how to write the result of time taken to load the page to a .csv file. Then if I were to re-run the test again for it to add another result to the .csv file.

代码:

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) 方法在追加模式下的模块.

You can use the fs module with the write(path, content, mode) method in append mode.

var fs = require('fs');
fs.write(filepath, content, 'a');

其中 filepath 是字符串形式的文件路径,content 是包含 CSV 行的字符串.

where filepath is the file path as a string and content is a string containing your CSV line.

类似于:

address+";"+(new Date()).getTime()+";"+t

这篇关于如何在 Javascript 中写入 CSV 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆