我创建了一个将JSON转换为CSV的函数。但是JSON.parse返回未定义的值。请有人帮忙。
function JSONtoCSVConverter(JSONDataPath, showLabels) {
var JSONData = fs.readFile(JSONDataPath, "utf-8", (err, fileContent) => {
if (err) {
console.log(err);
} else {
console.log(fileContent);
JSON.parse(fileContent.toString().trim());
}
});
console.log(JSONData);
if (showLabels) {
console.log(JSONData.slice(1, JSONData.length));
var rowsOfDataArray = Object.keys(JSONData[0]);
var rowsOfData = rowsOfDataArray.join(",") + "\n";
}
JSONData.forEach((object) => {
var cellsOfDataArray = Object.values(object);
cellsOfData = cellsOfDataArray.join(",") + "\n";
});
var csv = rowsOfData + "\n" + cellsOfData;
return csv;
}
但是,我收到的错误是:undefined TypeError: Cannot read properties of undefined (reading 'slice') at JSONtoCSVConverter (C:\Users\harsh\OneDrive\Documents\Visual Studio 2022\Web Development\contactStoreApp\routes\reports.js:45:26) at C:\Users\harsh\OneDrive\Documents\Visual Studio 2022\Web Development\contactStoreApp\routes\reports.js:26:7 at Layer.handle [as handle_request] (C:\Users\harsh\OneDrive\Documents\Visual Studio 2022\Web Development\contactStoreApp\node_modules\express\lib\router\layer.js:95:5) at next (C:\Users\harsh\OneDrive\Documents\Visual Studio 2022\Web Development\contactStoreApp\node_modules\express\lib\router\route.js:144:13) at Route.dispatch (C:\Users\harsh\OneDrive\Documents\Visual Studio 2022\Web Development\contactStoreApp\node_modules\express\lib\router\route.js:114:3) at Layer.handle [as handle_request] (C:\Users\harsh\OneDrive\Documents\Visual Studio 2022\Web Development\contactStoreApp\node_modules\express\lib\router\layer.js:95:5) at C:\Users\harsh\OneDrive\Documents\Visual Studio 2022\Web Development\contactStoreApp\node_modules\express\lib\router\index.js:284:15 at Function.process_params (C:\Users\harsh\OneDrive\Documents\Visual Studio 2022\Web Development\contactStoreApp\node_modules\express\lib\router\index.js:346:12) at next (C:\Users\harsh\OneDrive\Documents\Visual Studio 2022\Web Development\contactStoreApp\node_modules\express\lib\router\index.js:280:10) at urlencodedParser (C:\Users\harsh\OneDrive\Documents\Visual Studio 2022\Web Development\contactStoreApp\node_modules\body-parser\lib\types\urlencoded.js:91:7)
1条答案
按热度按时间uelo1irk1#
JSON.parse
返回未定义或fs.readFile
返回undefined
?fs.readFile
不应返回任何内容如果你想正确使用
fs.readFile
的结果,你必须把其余的代码放在回调函数中,如下所示:你可能已经注意到,这是相当混乱的-这种模式被称为callback hell,是JavaScript中使用非阻塞API时的一种老式编程。你也会注意到,我没有使用
return
来处理变量csv
-要做到这一点,你必须向JSONtoCSVConverter
传递一个回调函数作为第三个参数。下面是这样做的一个例子(它被称为 * 回调模式 *)。
但是,有一个更好的解决方案。
一个更好的解决方案是使用promises。NodeJS的最新版本有基于promises的API(例如,参见fs.promises.readFile,允许您这样使用它们: