shammakh2
shammakh2

Reputation: 3

fs.readDirSync dies when changing directory o.O

Working on a node.js project, I found something interesting.

Test 1

Here is my initial directory structure for reference:

├── test
    └── test.js
├── start.js
├── package.json

start.js

const fs = require('fs');

console.log(fs.readdirSync("./test"));

used node start.js to run the script.

Output

['test.js']

Test 2

I changed my directory structure and tried again:

├── src
    ├── test
        └── test.js
    ├── start.js
├── package.json

This time used node ./src/start.js to run the script.

Output

Error: ENOENT: no such file or directory, scandir './test'.

Please could someone explain why this happen and why this works:

require("./test/test.js");

and how I can get around this by only using relative pathing (no other modules or __dirname). I am relatively new to NodeJs.

Upvotes: 0

Views: 272

Answers (1)

jfriend00
jfriend00

Reputation: 707298

The ./ in your path you pass to fs.readdirSync() is relative to the current working directory, not relative to __dirname.

When you start your app with node ./src/start.js, your current working directory is the parent of src. So, when you then try fs.readdirSync("./test"), it's not looking where there's a test subdirectory.

how I can get around this by only using relative pathing (no other modules or __dirname). I am relatively new to NodeJs.

Well, if you want to specify a relative path that is relative to the current module's location, then you HAVE to use __dirname to construct a path relative to that because the current working directory is global to your app, is what fs.readdirSync() and pretty much every function except require() uses to resolve relative paths and is dependent upon what the system working directory was when your app was started.

Module-relative paths are constructed using __dirname. That's how you do it in nodejs.


require() has it's own set of rules (which you can see here) and those rules have nothing at all to do with fs.readdirSync() or other library functions which use the current working directory.

The rules for require() have all sorts of things in them that are specific to module loading (such as defaulting to look in the node_modules sub-directory).

Upvotes: 1

Related Questions