0

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()) {
Jaz
  • 135
  • 4
  • 16

2 Answers2

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.com/nodejs-tutorials/how-to-check-if-path-is-file-or-directory-using-nodejs

Me1o
  • 1,629
  • 1
  • 6
  • 8
  • I get this error nodejs binding.lstat(pathModule._makeLong(path)) – Jaz Jul 10 '18 at 10:05
  • can you give the user read permissions ? looks like a known issue: https://github.com/nodejs/node-v0.x-archive/issues/3977 – Me1o Jul 10 '18 at 10:10
2

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}`);
    }
  })})
Zdenek F
  • 1,649
  • 1
  • 15
  • 27