0

I am just two days into node.js. I am attempting to write my own module, which uses fs (filesystem) api. The code is as below:

    var fs=require('fs');
    var path=require('path');

    // pkg file name constant
    const PKG_FILE = 'pkg.json';

    module.exports = function(srcDir, targetDir, callback) {
      console.log('checking dir: ', srcDir, '...');
      fs.readdir(srcDir, function(err, files) {
      // early return, in case of error.
      if (err) return callback(err);

    // look for pkg.json file and if found, iterate through
    // the list of components
    var pkgFile = path.join(srcDir, PKG_FILE);
    console.log(pkgFile);
    var pkg = fs.readFile(pkgFile, function(err, data) {
      if (err) return callback(err);

      var obj = JSON.parse(data);
      for (var attr in obj) {
        console.log(attr, " : ", obj[attr]);
      }
    });
  });
}

In the above code, I am trying to return to the caller, via the statement

if (err) return callback(err);

However, when an fs error occurs, I get a different error indicating that callback is undefined. Exact error is below:

rvnath@rv ~/projects/comviva/mbs/node/siteright $ node pkgtest.js riu3
checking dir:  riu3 ...
/home/rvnath/projects/comviva/mbs/node/siteright/libs/pkgcreator.js:17
    if (err) return callback(err);
                    ^
TypeError: undefined is not a function
    at /home/rvnath/projects/comviva/mbs/node/siteright/libs/pkgcreator.js:17:20
    at FSReqWrap.oncomplete (fs.js:95:15)

Does this mean that I am not supposed to call "return callback(err) in nested closures?

Thanks to anyone for correcting me.

regards.

EDIT I am using my module as below.

rvnath@rv ~/projects/comviva/mbs/node/siteright $ cat pkgtest.js 
var packager = require('./libs/pkgcreator');

packager(process.argv[2], function(err, files) {

    //if (err) {
         //console.log("some error occurred", err);
        //return;
    //}

    console.log("files listing...");
    files.forEach(function(file) {
        console.log(file);
    });
});

In case of success, I get the result correctly.

checking dir:  /home/rvnath/projects/comviva/mbs/ecp/ecp_6.0 ...
/home/rvnath/projects/comviva/mbs/ecp/ecp_6.0/pkg.json
reading module:  smp3
reading module:  pushp
reading module:  bulkp
reading module:  drp
reading module:  mop
reading module:  ecp_ws
reading module:  ecp_admin

but for failure, it says callback undefined.

Mopparthy Ravindranath
  • 3,014
  • 6
  • 41
  • 78

1 Answers1

0

As expected, you are not passing a callback to the function which you are exporting -- it is indeed undefined. Simply add an anonymous function as third parameter to the function from your module, and the problem should be gone.

packager(process.argv[2], function(err, files) {
    // your code
}, function(err) {
    // The actual callback
    console.log('Sadly, something went wrong: ' + err);
});
Community
  • 1
  • 1
Avalanche
  • 1,468
  • 1
  • 11
  • 18