3
votes

I am trying to promisify the fs readdir function using bluebird. I just want to read all the files in a directory, and then output the array with console.log.

const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'));

fs.readdir('./XML').then(function(err, directories) {
  console.log(directories);
});

I get the following output:

fs.readdir('./XML').then(function(err, directories) { ^

TypeError: Cannot read property 'then' of undefined at Object. (/Users/shooshte/Sportradar/notThatKindOfPeon/bluebird.js:4:20) at Module._compile (module.js:570:32) at Object.Module._extensions..js (module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad (module.js:446:12) at Function.Module._load (module.js:438:3) at Module.runMain (module.js:604:10) at run (bootstrap_node.js:394:7) at startup (bootstrap_node.js:149:9) at bootstrap_node.js:509:3

What am I doing wrong?

3

3 Answers

2
votes
fs.readdirAsync('./XML').then()

Documentation, second sentence:

The promisified method name will be the original method name suffixed with suffix (default is "Async").

4
votes

Seems like the library add "Async" to the method name: It works for me like that:

const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'));

fs.readdirAsync('./XML').then(function(directories) {
  console.log(directories);
});
0
votes

You might want to promisify only the function you're going to use:

const readdir = require('bluebird').promisify(require('fs').readdir);

return readdir(dir).then(function(err, files) {
  console.log('FILES', files)
  return files;
});