Neither of your code examples is correct.
In the first code example:
const getGiraffe = fs.readFile("./txt/giraffe.txt", "utf-8", (err, data) => {
return data;
});
You are reading the file (with no error handling) and then you do return data
back to the callback, but that doesn't go anywhere. So, getGiraffe
will simply be undefined
.
To use the asynchronous version of fs.readFile()
, you must use the data
value inside the callback or call some function from within that callback and pass it the data. You cannot simply return the data out.
fs.readFile("./txt/giraffe.txt", "utf-8", (err, data) => {
if (err) {
console.log(err);
} else {
console.log(data);
}
});
In the second code example:
const getRhino = fs.readFileSync("./txt/rhino.txt", "utf-8", (err, data) => {
return data;
});
You are passing a callback to a function fs.readFileSync()
that does not accept a callback. That callback will be ignored.
The calling signature for fs.readFileSync()
is this:
fs.readFileSync(path[, options])
It takes only two arguments, neither is a callback.
Your question
If i stored them in the the variables, will they still run in the background while executing the file or would this be Synchronously?
The first code example will run in the background asynchronously, but getGiraffe
will be undefined
. It will not have the data from your file in it. That is just not how fs.readFile()
works. You must use the data it delivers INSIDE the callback itself.
Your second code example, is synchronous and blocking. It will block the event loop and getRhino
will contain the data from the file, but your callback will be ignored and never called because that's not a supported parameter for fs.readFileSync()
.
For more information on communicating back a result to the caller from an asynchronous function like fs.readFile()
see this reference:
How to return the response from an asynchronous call