Node.js Asynchronous request assignment help

Node.js Asynchronous request assignment help
0

#1

I’m working on the Start a Node Server assignment and I’m stuck on the MY FIRST ASYNC I/O! (Exercise 4 of 13) assignment.

I’ve read a bunch of stuff about making async i/o requests and it seems very simple but I can’t get it to work. The instructions are ambiguous and it’s frustrating.

Here’s my code:

var fs = require(‘fs’);

fs.readFile(‘process.argv[2]’, ‘utf8’, function(err, data){
if(err){
console.error(err);
}else
console.log(data.split(’\n’).length - 1);

});

What’s the issue?


#3

I thought that took care of the callback function? I thought all I needed for that was the function(err, data) like in the synchronous assignment.

Your answer works with the exception that I had to add an if statement to take care of error handling. Thanks for the help. I have some reading to do on callbacks so I can fully understand this.

Here’s the official answer they give after you complete the assignment in case you’re curious.

var fs = require(‘fs’)
var file = process.argv[2]

 fs.readFile(file, function (err, contents) {  
   // fs.readFile(file, 'utf8', callback) can also be used  
   var lines = contents.toString().split('\n').length - 1  
   console.log(lines)  
 })

#4

Just a quick thought: You’re passing in 'process.argv[2]', i.e. as a string (with the quotes). I assume that was a typo?
If not, that certainly would have prevented you from opening your file,as it would look for a file with the name “process.argv[2]”.

Other than that, your code looks like it should give you the number of lines just fine.