如何写入JavaScript中的CSV文件

如何写入JavaScript中的CSV文件

本文介绍了如何写入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();
    });

}


推荐答案

请使用模块与 write(path,content,mode) method in append 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文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 01:22