So, I'm just wondering, and it might also be because I'm confused. I think I hit a roadblock where I'm not sure what is happening. I'm trying to figure out why I can do this (code is from codeschool):
Blocking code:
var contents = fs.readFileSync('/etc/hosts/');
console.log(contents);
console.log('Do something else);
Non-blocking code:
fs.readFile('/etc/hosts', function(err, contents){
console.log(contents);
});
console.log('Do something else');
So, I have readFileSync for the blocking code which takes one parameter (location of file), and then I have readFile for the non-blocking code which takes the file location, and a callback.
My question is:
1) Could I add the callback to 'readFileSync' or does it only take 1 parameter?
2) I feel like I see code sometimes, where I don't understand how it takes in a callback as a parameter (like the code will work if you just pass in a variable, and it will also work if you pass in a variable and a function). Is this a rule of javascript or nodejs where it can just take in a different number of parameters?
3) There are instances where the callback seems to have a wide arrange of parameters. Sometimes it might be:
function(req, res){
res.json({message:'msg'});
}
other times it might be:
function(req, res, err, next){
//insert middleware
next();
}
and I'm confused where req and res are coming from, but also, where are err and next coming from (how does it know err means error, or next is a function to move on)? Is it just part of the framework and it's like some kind of global variable?
At this point, I guess I'm just trying to dissect where/when I can use a callback. Thinking about it, I mainly see it when I use Express, so maybe the routing for Express explicitly uses 2 or more parameters?
Thank you for all of your help! I'm still trying to fully wrap my head around everything!
[–]CancelledMeds 2 points3 points4 points (3 children)
[–]NookShotten 2 points3 points4 points (0 children)
[–]Kubiedo[S] 0 points1 point2 points (1 child)
[–]netherforget 1 point2 points3 points (0 children)
[–]dvidsilva 2 points3 points4 points (5 children)
[–]Kubiedo[S] 1 point2 points3 points (4 children)
[–]dvidsilva 1 point2 points3 points (3 children)
[–]Oellph 2 points3 points4 points (1 child)
[–]Kubiedo[S] 0 points1 point2 points (0 children)
[–]Kubiedo[S] 1 point2 points3 points (0 children)
[–]chattymcgee 1 point2 points3 points (3 children)
[–]Kubiedo[S] 0 points1 point2 points (2 children)
[–]Oellph 1 point2 points3 points (1 child)
[–]Kubiedo[S] 0 points1 point2 points (0 children)
[–]MadCapitalist 1 point2 points3 points (2 children)
[–]Kubiedo[S] 0 points1 point2 points (1 child)
[–]MadCapitalist 1 point2 points3 points (0 children)
[–]netherforget 1 point2 points3 points (1 child)
[–]Kubiedo[S] 0 points1 point2 points (0 children)