Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am reading directory and exporting file names using callbacks but my module is not sending data when i import readDirectory function, Any idea what is going wrong with below code ? my callback return values in module itself but its not sending while using exports.

What I have tried:

main.js

var fs = require('fs');
var path = './Logs';
function readDirectory() {
fs.readdir(path, function(err,items) {
return filesData(items);
});
}
function filesData(items) {
var data = JSON.stringify(items)
console.log('data from module',data);
return data;


}
exports.readDirectory = readDirectory;

app.js

var readDirectory = require('./main');
var obj = readDirectory.readDirectory();

console.log(JSON.stringify(obj));
Posted
Updated 30-Jun-16 20:14pm

1 solution

Try executing the following code:


directoryOps.js
(function(directoryOps) {

  var fs = require('fs');
  var path = './Logs';

  function filesData(items) {
    var data = JSON.stringify(items)
    console.log('data from module',data);
    return data;
  }

  directoryOps.readDirectory = function() {
    fs.readdir(path, function(err,items) {
      return filesData(items);
    });
  };

})(module.exports);


App.js
var directoryOps = require('./directoryOps');
var obj = directoryOps.readDirectory();


Sorry for the changes I made in the file name.

**Note:

Also the way you are currently creating "main.js", it would add variables like "fs, path, filesData, readDirectory" to the global scope and hence polluting it . So its better to execute the function as a part of IIFE (anonymous function). This would not add variable to the global scope, keeping your scope clean.

Hope it helps...



 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900