As per the documentation of express.static [1], which leads to the docs of the serve-static module [2], the directory you provide is the root directory, meaning it's intentionally made impossible to access anything outside of it.
To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.
The function signature is:
express.static(root, [options])
The root argument specifies the root directory from which to serve static assets. For more information on the options argument, see express.static. [3]
[1] https://expressjs.com/en/starter/static-files.html
[2] https://expressjs.com/en/resources/middleware/serve-static.html#API
[3] https://expressjs.com/en/4x/api.html#express.static
Not related, but fyi: the path you're providing to fs
etc. is relative to where the script is called from.
For example, if you call node server.js
from the root folder of the application, the path "./public/index.html"
should work fine, but if you're calling it from a different path, it will fail, e.g. node /home/user/projects/this-project/server.js
.
Thus, you should always join the path with __dirname
, like so:
+const path = require("path");
-fs.readFile("./public/index.html", "UTF-8", function (err, data) {
+fs.readFile(path.join(__dirname, "./public/index.html"), "UTF-8", function (err, data) {
}
this makes the path relative to the directory of the current file you're trying to access it from, which is what you expect.