提问者:小点点

nodejs-将csv流到字符串变量


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

代码在每个对象上经历一个循环,然后在每个属性上经历一个内部循环,并提取其属性(有数百个属性),然后将一行的所有信息--作为对象名称及其值的映射--放入一个名为returnVar的变量中。 我们使用'fast-csv'库,带有名为csvstream的WriteStream。 也使用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();
    });
});

共1个答案

匿名用户

https://c2fo.io/fast-csv/docs/formatting/methods#WriteToBuffere
https://c2fo.io/fast-csv/docs/formatting/methods#WriteToString

csvstream.write(result._source);更改为
csvstream.writeToString(result._source)。然后(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

相关问题