admin管理员组

文章数量:1336076

I want to check if the path is a file or a directory. If it's a directory then Log the directory and file separately. Later I want to send them as json object.

const testFolder = './data/';
fs.readdir(testFolder, (err, files) => {
  files.forEach(file => {
    console.log(`FILES: ${file}`);
  })});

Edit: If I try to this

fs.readdir(testFolder, (err, files) => {
  files.forEach(file => {
    if (fs.statSync(file).isDirectory()) {
    console.log(`DIR: ${file}`);
  } else {
    console.log(`FILE: ${file}`)
  }
  })}); 

I get this error:

nodejs binding.lstat(pathModule._makeLong(path))

Update: Found the solution. I had to add testFolder + file like this :

if (fs.statSync(testFolder + file).isDirectory()) {

I want to check if the path is a file or a directory. If it's a directory then Log the directory and file separately. Later I want to send them as json object.

const testFolder = './data/';
fs.readdir(testFolder, (err, files) => {
  files.forEach(file => {
    console.log(`FILES: ${file}`);
  })});

Edit: If I try to this

fs.readdir(testFolder, (err, files) => {
  files.forEach(file => {
    if (fs.statSync(file).isDirectory()) {
    console.log(`DIR: ${file}`);
  } else {
    console.log(`FILE: ${file}`)
  }
  })}); 

I get this error:

nodejs binding.lstat(pathModule._makeLong(path))

Update: Found the solution. I had to add testFolder + file like this :

if (fs.statSync(testFolder + file).isDirectory()) {
Share Improve this question edited Jul 10, 2018 at 10:53 Jaz asked Jul 10, 2018 at 9:47 JazJaz 1354 silver badges16 bronze badges 6
  • I think you used the wrong tag "java" :) – Leviand Commented Jul 10, 2018 at 9:49
  • Java user: "Java (not to be confused with JavaScript or JScript or JS)" – Glains Commented Jul 10, 2018 at 9:49
  • sorry for typo. – Jaz Commented Jul 10, 2018 at 9:51
  • Possible duplicate of Node.js check if path is file or directory – Lorddirt Commented Jul 10, 2018 at 10:06
  • Duplicate of stackoverflow./questions/15630770/…? – Lorddirt Commented Jul 10, 2018 at 10:06
 |  Show 1 more ment

2 Answers 2

Reset to default 4

quick google search..

var fs = require('fs');
var stats = fs.statSync("c:\\dog.jpg");
console.log('is file ? ' + stats.isFile());

read: http://www.technicalkeeda./nodejs-tutorials/how-to-check-if-path-is-file-or-directory-using-nodejs

Since Node 10.10+, fs.readdir has withFileTypes option which makes it return directory entry fs.Dirent instead of just the filename. Directory entry contains useful methods such as isDirectory or isFile.

Your example then would be solved by:

const testFolder = './data/';
fs.readdir(testFolder, { withFileTypes: true }, (err, dirEntries) => {
  dirEntries.forEach((dirEntry) => {
    const { name } = dirEntry;
    if (dirEntry.isDirectory()) {
      console.log(`DIR: ${name}`);
    } else {
      console.log(`FILE: ${name}`);
    }
  })})

本文标签: javascriptHow to check if path is a directory or fileStack Overflow