'How does ./ and ../ actually work? I have a perculiar case
I have a peculiar case that I can't figure out. First, let's say I have a file system such as follows.
webdev/
├── app.js
├── comment.html
├── controller/
│ └── controller.js
└── model/
└── model.js
In app.js
:
const fs = require("fs");
const commentHtml = fs.readFileSync(`./comment.html`,"utf-8");
console.log(commentHtml);
So of course this works right? ./
means relative path. It also works if I do:
const commentHtml = fs.readFileSync(`comment.html`,"utf-8");
ok that's also not weird. Now, in controller.js
:
const commentHtml = fs.readFileSync(`./comment.html`,"utf-8");
const model = require("./../model/model.js");
these both work. first of all, for the readFileSync("./comment.html")
should mean that the file sits in controller/
but it sits in webdev/
. Yet it still works.
Meanwhile, if I use require("./model/model.js")
it would give me an error. According to how ./
and ../
works, require("./model/model.js")
is wrong. So why does readFileSync("./comment.html")
work? Btw I did console.log
on it and it definitely read it both times, it's not a case of errors not showing.
Solution 1:[1]
You can import files using the relative path or the absolute path.
./
=> is used to import a file under the same folder that you are in.../
=> is used to import a file in a parent directory.
let's have an example:
consider I have three files
First one => C: Documents/projects/folder1/file1.js
.
Second one => C: Documents/projects/folder1/file2.js
.
Third one => C: Documents/projects/folder2/file3.js
and I want to import file3
and file2
in file1
It would be like this
// in file1.js
const file2 = fs.readFileSync(`./file2.js`,"utf-8"); // as it is in the same directory
const file3 = fs.readFileSync(`../folder2/file3.js`,"utf-8"); // as it is in a parent directory
Solution 2:[2]
I actually discovered the reason so I'll answer it here to help others. ./
when using require()
means the location of the file it is sitting in. with fs
functions, it is where your current terminal directory is.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Adel Emad |
Solution 2 | Tyler2P |