I've been playing around with Node.js again for the past week and I currently have 2 problems with this code which takes a file path from the command line interface, checks it exists and tries to parse it.
1) When I conole.log the "output" I get undefined though my earlier call to console.log( data.toString() ); looks good.
2) Nesting hell: Looking at the code below, though it works in principal it is not flexible. How would you break it up or what rules do you use for breaking an annon functions into something you would work on its own feet
var parse = require('csv-parse');
var fs = require('fs');
var args = process.argv.slice(2);
process.argv.forEach(function (val, index, array) {
if( index > 1){ // Start looping from the 3rd argument
filePath = array[index]; // Get the filePath from the arguments
console.log( filePath );
fs.exists(filePath, function(exists) { // Check the filePathExists
console.log( exists,filePath );
if (exists) {
console.log( filePath );
fs.readFile(filePath, function (err, data) { // Read the contents of the file
if (err) throw err;
console.log( data.toString() );
parse(data.toString(), {comment: '#'}, function(err, output){
console.log(output);
});
});
} else{
console.log( filePath + ' does not exist');
}
});
}
});