首页 > 解决方案 > 尝试更改此模块以使用 return 语句

问题描述

我有一个使用 Promise 将 CSV 转换为 JSON 的模块,但是因为我使用 Promise 而不是返回数据。现在的数据是隐式的,我无法比较两个 CSV 文件。我如何能够将代码更改为使用 return 语句。

csv转json文件

const readline = require('readline');
const fs = require('fs');

function readCsv(pathToFile) {
    return new Promise((resolve, reject) => {
        // This is where your code would go (other than the "requires")
        // replace the "cats.csv" string with the "pathToFile" variable instead
        // stick this inside of your "close" handler function once the data's been assembled:
        const csvReader = readline.createInterface({
            input: fs.createReadStream(pathToFile)
        });

        let headers;
        const rows = [];
        let tempRows = [];
        csvReader
            .on('line', row => {
                if (!headers) {
                    headers = row.split(','); // header name breed age
                } else {
                    rows.push(row.split(','));
                }
            })
            .on('close', () => {
                // then iterate through all of the "rows", matching them to the "headers"
                for (var i = 0; i < rows.length; i++) {
                    var obj = {};
                    var currentline = rows[i];

                    for (var j = 0; j < headers.length; j++) {
                        obj[headers[j]] = currentline[j]; //Kitty Siamese 14
                    }

                    tempRows.push(obj);

                }

                resolve(JSON.stringify(tempRows));
            });

        // This would be in place of the "return" statement you had before
    });
}

module.exports = readCsv;

标签: node.jsjavascript-objects

解决方案


推荐阅读