Node.js Asynchronous request assignment help

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){
console.log(data.split(’\n’).length - 1);


What’s the issue?

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  

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.