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 trialTomasz Grodzki
8,130 PointsWhy readFileSync doesn't show me the line in console?
I have two codes.
First:
var fs = require("fs");
fs.readFile('./as.txt', function (err, data) {
if (err) throw err;
console.log("File read.");
});
console.log("I love bees.");
Second:
var fs = require("fs");
fs.readFileSync('./as.txt', function (err, data) {
if (err) throw err;
console.log("File read.");
});
console.log("I love bees.");
And I have got question, why in second example I don't get "File read" in console?
1 Answer
Byron Injeeli
Full Stack JavaScript Techdegree Graduate 25,639 PointsHi Tomasz. The reason you don't see "File read" in the second function is because fs.readFileSync() does not have a callback because it is a synchronous function. It is different from fs.readFile() which is an asynchronous function. This is how you use them differently:
fs.readFile('./as.txt', function (err, data) {
if (err) throw err;
var fileData = data;
console.log("File read.");
});
var fileData = fs.readFileSync('./as.txt');
console.log("File read.");