Playing around with Ex 12 why the two fs.readFile interferred with each other?

Hi @zedshaw,

I am currently on exercise 12 (really loving the way how the material is being presented btw)

totally new to coding and was trying to wrap my head around what fs.readFile(path[, options], callback) is.

I was trying ways to break the ex12 code

// Exercise 12: Functions, Files, Variables

const fs = require('fs');

const print_lines = (err, data) => {
	console.log(data.toString());
}

const yell_at_me = (what) => {
	return what.toUpperCase();
}

fs.readFile("poem.txt", print_lines);

//let's do that again but with an anonymous function
//you've actually seen this before

fs.readFile("poem.txt", (err, data) => {
	let yelling = yell_at_me(data.toString());
	print_lines(err, yelling);
});

I changed the “poem.txt” to “test.txt” on the anonymous function and it worked.

I then changed the poem.txt to “poem” on the anonymous function, run it and comes out with the following message:

/Users/peter/Google Drive/LJSTHW/ex12.js:19
let yelling = yell_at_me(data.toString());
^

TypeError: Cannot read property ‘toString’ of undefined
at ReadFileContext.callback (/Users/peter/Google Drive/LJSTHW/ex12.js:19:32)
at FSReqCallback.readFileAfterOpen [as oncomplete] (fs.js:264:13)

I can understand the error I purposefully made on line 18-21:


fs.readFile("poem", (err, data) => {
	let yelling = yell_at_me(data.toString());
	print_lines(err, yelling);
});

What I don’t understand is why does line 13:

fs.readFile("poem.txt", print_lines);

is totally correct but was interfered by the mistake made on line 18~21 because it’s not printing out the poem.txt file.

I commented out code line 18~21 and run the code again and it works again.

First: Please wrap your code in code tags when you post here, makes it easier to read.

[code]
your code
[/code]

fs.readFile is an asynchronous function. This should be covered later in the course, but in short: When you call an asynchronous function, it’s started at the call point, but it doesn’t block subsequent code until it’s finished like synchronous functions do.

In your case, the first call to readFile is executed parallel to what’s coming next. But then the second call blows up before the first call even reaches the callback, so nothing happens there either.

Try adding an error handler to the second call:

fs.readFile("poem", (err, data) => {
    if (err) {
        console.log(err);
    } else {
        let yelling = ...
    }
});

Now the second call fails gracefully and you should see that the first call is executed properly.

A free service run by Zed A. Shaw for learncodethehardway.org.