I've separate some logic to different file in my project, the problem is that I got the following error
Cannot read property 'readFile' of undefined
this is the structure of my project
projName
utils
file.js
the file.js code is
module.exports = function () {
var fs = require('fs');
function readFile(filePath) {
fs.readFile(filePath, 'utf8', function (err, data) {
if (err) {
return console.log("error to read file: " + filePath + " " + err);
}
return data;
});
}
};
I want to call to this module at
projname
controller
request
I do it with the following code And here I got the error
module.exports = function (app) {
app.get('/test', function(req, res) {
var file = require('../utils/file')();
var fileContent = file.readFile("C://test.txt");
any idea what am I doing wrong here? This is not related to async call
Your file.js could be like this:
and your request.js file like this:
Regarding the async call when you call a method from Node.JS libaries, it is usually a async call, that means that the result of the function is not going to return immediately:
instead it is going to return at some time later, so the only way you can get the results later is passing by a function that is going to be called when the results are ready:
Regarding module.exports when you export some logic of a file that you created in Node.JS, you can return your function on the following ways:
UPDATE: In your file.js you are exporting a function that is going to receive a file path and a function called callback as the second parameter (yes, you read it well, a function as a parameter) which is going to be called once the fs.readFile get the file content.
then in your request.js file, you are using your module (file.js) you just created, and the function that your module is exporting accepts a string as parameter called filePath, and a function as parameter called callback:
file.readFile(filePath, callback)
so when your module file.js get the content file is going to call to your callback function parameter.
I hope that this helps to clarify a little bit your knowledge about callbacks.