5

index.js

const fs = require('fs');
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));

filesystem:

src
-commands
  -stuff.js
-config.json
-index.js

Error:

Error: ENOENT: no such file or directory, scandir './commands/'
    at Object.readdirSync (fs.js:783:3)

The folder is there, and has files in it. I tried './commands/' , './commands' , 'commands' , nothing seems to work.

SudoGaron
  • 339
  • 6
  • 22
  • "./{DIRECTORY_NAME}" with the leading ./ works fine. I just tested it. Must be something else, like a misspelling. – Jacob Penney Dec 09 '19 at 20:54
  • Are you on Windows? The Path delimeter on windows is "\". – zero298 Dec 09 '19 at 20:54
  • 1
    Does this answer your question? [Nodejs FS module returning no such file or dir error](https://stackoverflow.com/questions/50966704/nodejs-fs-module-returning-no-such-file-or-dir-error) – Wendelin Dec 09 '19 at 20:55
  • I am on windows for local dev. I managed to solve the issue with: ``` path.resolve(commandsFolder) ``` – SudoGaron Dec 09 '19 at 20:57

3 Answers3

5

Try processing path with path module, as below

const path = require('path');

const dirPath = path.resolve(__dirname, './commands');

And then pass dirPath to readdirSyncfunction. path is an internal node.js module, so you don't need to install anything

  • I just found this right before your answer. You are 100% correct. I didn't realize between Windows (local) and Ubuntu(remote server) that the paths would not resolve correctly without this. – SudoGaron Dec 09 '19 at 20:58
4

You are on Windows. The path delimeter for Windows is \, not /. Try making your program platform agnostic with something like this:

const fs = require('fs');
const path = require("path");

const commandDir = path.join(__dirname, "commands");
const commandFiles = fs.readdirSync(commandDir).filter(file => file.endsWith('.js'));

console.log(commandFiles);
zero298
  • 25,467
  • 10
  • 75
  • 100
0

With RegEx

const fs = require('fs');

let searchPath = "./mydirectory";
let searchFileName = ".*myfile.*";

let searchFoundFiles = fs
    .readdirSync(searchPath)
    .filter((f) => new RegExp(searchFileName).test(f));

if (searchFoundFiles.length) {
    console.log("File already exists");
}
Manohar Reddy Poreddy
  • 25,399
  • 9
  • 157
  • 140