admin管理员组

文章数量:1295255

I am trying to write a function that takes a path and returns all the files inside that directory.

When I do this:

function getDirectories(path) {
  fs.readdir(path, function(err, content) {
    if (err) {
      return err;
    } else {
      return content;
    }
  });
}

console.log(getDirectories('./XML/'));

I get undefined in the console.

But when I do this:

function getDirectories(path) {
  fs.readdir(path, function(err, content) {
    if (err) {
      return err;
    } else {
      console.log(content);
    }
  });
}

I get the expected array with file names as strings.

What am I doing wrong?

I am trying to write a function that takes a path and returns all the files inside that directory.

When I do this:

function getDirectories(path) {
  fs.readdir(path, function(err, content) {
    if (err) {
      return err;
    } else {
      return content;
    }
  });
}

console.log(getDirectories('./XML/'));

I get undefined in the console.

But when I do this:

function getDirectories(path) {
  fs.readdir(path, function(err, content) {
    if (err) {
      return err;
    } else {
      console.log(content);
    }
  });
}

I get the expected array with file names as strings.

What am I doing wrong?

Share Improve this question asked Nov 16, 2016 at 10:04 Miha ŠušteršičMiha Šušteršič 10.1k27 gold badges97 silver badges175 bronze badges 1
  • its because readdir is async - try using fs.readdirSync – naortor Commented Nov 16, 2016 at 10:08
Add a ment  | 

2 Answers 2

Reset to default 7

fs.readdir is async use this :

function getDirectories(path, callback) {
    fs.readdir(path, function (err, content) {
        if (err) return callback(err)
        callback(null, content)
    })
}

getDirectories('./XML', function (err, content) {
    console.log(content)
})

I had the same problem and I solved it by using fs.readdirSync

function getDirectories(path) {
  fs.readdirSync(path, function(err, content) {
    if (err) {
      return err;
    } else {
      return content;
    }
  });
}

Should work

本文标签: javascriptfsreaddir returns undefined when called inside a functionStack Overflow