Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Robert Merrill
6,215 PointsServer Side Node JavaScript question
I'm working on the following question and running into a roadblock:
Questions: Assuming the following code is being executed as server side Node Javascript, what would be the output? (assume main.txt is a valid and readable file).
When I put the code in my terminal I'm getting:
"read finished undefined"
This output doesn't doesn't match any of the possible output options. Any thoughts?
var fs = require('fs'); console.log("read started"); fs.readFile('main.txt', function(err,data) { var str = data.toString(); console.log("main data converted to string"); }); console.log("read finished");
read finished main data converted to string read started read started
read finished main data converted to string
Program will throw an error
read started main data converted to string read finished
I do not know
1 Answer
jobbol
Full Stack JavaScript Techdegree Student 19,117 PointsRunning this locally on my machine and it seems to work fine. I think the problem is with how you set yours up. You said you did it in your terminal, did you forget to create a main.txt to read from?
If your file doesn't exist, data won't have anything assigned to it and will crash if you try to use toString(). You can test err beforehand to see exactly what went wrong.
Code used was:
var fs = require('fs');
console.log("read started");
fs.readFile("main.txt", function(err, data) {
if(err){
showError(err);
return;
}
console.log(data.toString());
console.log("main data converted to string");
});
console.log("read finished");
function showError(err){
console.log("Something bad happened:\n"+
"=====================\n"+
err+"\n"+
"====================\n");
}
Output successful:
read started
read finished
asdfjkl
asdfjkl.
asdfjkljkl
asdjfioadsjfiojadsfioj
main data converted to string
Output non-existent file:
read started
read finished
Something bad happened:
=====================
Error: ENOENT, open 'C:\Users\Josh\Documents\PROJECTS\JS\main.txt'
====================