【问题标题】:nodejs - streaming csv to string variablenodejs - 将 csv 流式传输到字符串变量
【发布时间】:2020-10-02 07:17:31
【问题描述】:

我有一个接受嵌套对象列表的代码,每个对象都应转换为日志行。

代码对每个对象进行一个循环,然后对每个属性进行一个内部循环,并提取其属性(有数百个属性),然后将一行的所有信息 - 作为对象名称的映射和将其值放入一个名为 returnVar 的变量中。 我们使用名为 csvStream 的 WriteStream 库“fast-csv”。还有一个 fs.createWriteStream 管道。

最后,我们循环遍历每个对象并使用 csvStream.write() 将其写入, 这将在文件的第一行插入属性名称,并在其他行中插入日志(以相同的顺序)。

我需要更改代码,而不是通过管道传输到文件流,而是打印到字符串类型变量。

这是代码:

let Promise = require('bluebird');
let csv = require('fast-csv');
let fs = Promise.promisifyAll(require('fs'));

...

return new Promise(function (resolve, reject) {
    var csvStream = csv.createWriteStream({ headers: propNames })
        .transform(function (item) { // every item is a nested object that contains data for a log line
            var returnVar = {}; // every returnVar will represents a map of property and value, that will be transform to a log line
            for (var prop in item) { 
                if (item.hasOwnProperty(prop)) {
                    if (propNames.indexOf(prop) >= 0) {
                        if (typeof item[prop] === 'object') {
                            returnVar[prop] = JSON.stringify(item[prop]);
                        }
                        else {
                            returnVar[prop] = item[prop];
                        }
                    }
                    //the object might be a complex item that contains some properties that we want to export...
                    else if (typeof item[prop] === 'object') {
                        var nestedItem = item[prop];
                        for (var nestedProp in nestedItem) {
                            if (propNames.indexOf(prop + "_" + nestedProp) >= 0) {
                                returnVar[prop + "_" + nestedProp] = nestedItem[nestedProp];
                            }
                        }
                    }
                }
            }

            return returnVar; // return log line
        });

    // create file path
    var fileId = "Report_" + cryptoService.generateRandomPassword(16) + ".csv";
    var filePath = tempPath + fileId;

    getOrCreateTempDirectory().then(function () {
        var writableStream = fs.createWriteStream(filePath);

        writableStream.on("finish", function () {
            resolve({
                fileId: fileId
            });
        });

        csvStream.pipe(writableStream);

        _.each(results.records, function (result) {
            // write line to file
            csvStream.write(result._source);
        });

        csvStream.end();
    });
});

【问题讨论】:

    标签: javascript node.js fast-csv


    【解决方案1】:

    https://c2fo.io/fast-csv/docs/formatting/methods#writetobuffer
    https://c2fo.io/fast-csv/docs/formatting/methods#writetostring

    改变 csvStream.write(result._source);
    csvStream.writeToString(result._source).then(data => console.log(data));

    Promise.all(_.map(results.records, result => csvStream.writeToString(result._source)))
      .then(rows=>console.log(rows))
    // rows should be an array of strings representing all the results
    

    你也可以使用 async/await

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-12
      • 1970-01-01
      • 2014-08-29
      • 2019-03-20
      • 2021-08-03
      • 1970-01-01
      相关资源
      最近更新 更多