node.js - 尝试更改此模块以使用 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;
解决方案
推荐阅读
- javascript - 模块“domhandler”没有导出成员“DomElement”。您的意思是改用“从“domhandler”导入 DomElement”吗?
- python - 网格搜索熊猫数据框中的每一行
- postgresql - ThreadAbortException:系统错误将 Postgres 函数(表返回)的结果读取到 EF 可枚举中
- r - 对 R 中的连续值求和,按特定值分解
- php - 如何格式化 PostgreSQL 查询以干净地返回 geojson?
- vert.x - Vertx mysql客户端异步和同步
- mongodb-query - MongoDB - 解释与日志 - 检查的键不匹配
- reactjs - 使用 Apollo GraphQL 客户端进行 React 时出现意外输出
- html - 使用用户配置文件创建 html/js 帐户
- pandas - 从每个组中删除第一个 n