alangilbi
alangilbi

Reputation: 331

Cannot read property 'map' of undefined Node js

I am getting the Error, I am writing a function to monitor a path for. I am new to Node.js:

TypeError: Cannot read property 'map' of undefined

at C:\Users\a\Desktop\DL\file\filemonitor.js:15:14 at FSReqWrap.oncomplete (fs.js:149:20)

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

monitordir(monitorpath) {
  var fileList = [];
  return new Promise((resolve, reject) => {
    fs.readdir(monitorpath,function(err, items) {
      items.map((file) => {
        fileList.push(file);
      });
      resolve(fileList);
    });
  })
}

Note: I don't see a package.json file either. Should I have a sucessful run to see it

Upvotes: 0

Views: 5993

Answers (2)

Nicolas Takashi
Nicolas Takashi

Reputation: 1740

When you run var fs = Promise.promisifyAll(require("fs")); it return a promise to you. So you can't execute a map of a promise.

I believe that you don't need a Promise to resolve fs module, my suggestion is you write something like that.

const Promise = require('bluebird');
const fs = require("fs");

const monitordir = path => {
    return new Promise((resolve, reject) => {
        fs.readdir(path, (error, items) => {
            if (error) return reject(error)
            return resolve(items);
        })
    })
}

Upvotes: 1

Zeeshan Hassan Memon
Zeeshan Hassan Memon

Reputation: 8325

Try following fix, see if it fits your needs:

monitordir(monitorpath)
{
    var fileList = [];
    return fs.readdir(monitorpath)
        .then(function(err,items) {
            items.map((file) => {
                fileList.push(file); // fileList is ready here! do whatever you want before it resolves to caller
            });
            return fileList;
        })
        .catch(function(e) {
            // something bad happened; throw error or handle it as per your needs
            throw new Error(e);
        });
}

For package.json you can run npm init command at your project directory it will create one for you.

Upvotes: 0

Related Questions