简体   繁体   English

nodejs - 将 csv 流式传输到字符串变量

[英]nodejs - streaming csv to string variable

I have a code that accepts a list of nested objects, each of which should be converted to a log row.我有一个接受嵌套对象列表的代码,每个对象都应转换为日志行。

The code goes through a loop on each object, then an inner loop on each property, and extracts its property (there are hundreds of properties), then puts all the information of a row - as a map of the object's name and its value, into a variable called returnVar.代码在每个 object 上进行循环,然后在每个属性上进行内部循环,并提取其属性(有数百个属性),然后放入一行的所有信息 - 作为对象名称及其值的 map,到一个名为 returnVar 的变量中。 We use the 'fast-csv' library, with WriteStream that is named csvStream.我们使用名为 csvStream 的 WriteStream 库“fast-csv”。 also with a fs.createWriteStream pipe.还带有 fs.createWriteStream pipe。

Finally, we loop over each object and write it with csvStream.write(), that will insert the properties name in the first line of the file, and the logs (in the same order) in the other lines.最后,我们遍历每个 object 并使用 csvStream.write() 将其写入,这将在文件的第一行插入属性名称,并在其他行中插入日志(以相同的顺序)。

I need to change the code so that instead of doing pipe to file stream, it will print to a string type variable.我需要更改代码,而不是执行 pipe 文件 stream,而是打印到字符串类型变量。

This is the code:这是代码:

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

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

Change csvStream.write(result._source);更改csvStream.write(result._source); to
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

You can also use async/await你也可以使用 async/await

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM