I created a function to convert JSON in CSV. However JSON.parse is returning undefined. Please can someone help.
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;
}
However, the error I have received is:
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)
readFileisasyncso you won't be immediately able to log the result of the read like that which is why it'sundefined.asyncthey don't mean that it's anasyncfunction (see my answer below). It's async in the fact that's its doing work asynchronously.readFilewas added in version 10. Which may help.