Home node.js FS.Readdir () error: "Error: Enoent: No Such File Or Directory" When you...

FS.Readdir () error: “Error: Enoent: No Such File Or Directory” When you start the application from another folder

Author

Date

Category

When I start the program on the server from its folder (node ​​index.js), everything works fine.

But, if you run from another directory (node ​​/opt/webserver/index.js), it gives an error:

{Error: Enoent: No Such File Or Directory, Scandir ‘./routers’
Errno: -2,
Code: ‘Enoent’,
Syscall: ‘scandir’,
Path: ‘./routers’}

fs.Readdir ('./ Routers', (Error, Files) = & gt; {
  if (error) Return Console.log (Error);
  Files.Foreach (File = & GT; {
    App.USE (Require (`./routers / $ {File}`));
  });
});

Answer 1, Authority 100%

To understand what is happening, you need to write a little script and boight from different places:

const path = require ('path');
Console.log (`CWD = $ {process.cwd ()}, dirname = $ {__ dirname}`);
Console.log (`Path1 = $ {Path.Resolve ('/ Routes')}, Path2 = $ {Path.Resolve (__ dirname, './routes')}`);

Result:

: ~ $ node tmp / q / src / dirname.js
CWD = / Users / Z, Dirname = / Users / Z / TMP / Q / SRC
Path1 = / Users / Z / Routes, Path2 = / Users / Z / TMP / Q / SRC / ROUTES

It can be seen that ./ Routes “resolve” from the site of starting the program.

You need to add the use of the global variable __ dirname to “resolve” from the location of the running file.

For example, so:

const routerspath = path.resolve (__ dirname, './routes');
FS.Readdir (RouteSpath, (Error, Files) = & gt; {
  if (error) Return Console.log (Error);
  Files.Foreach (File = & GT; {
    App.USE (Require (`$ {ROUTERSPATH} / $ {File}`));
  });
});

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions