简体   繁体   中英

Why does require() not require an absolute path but an express.static() does?

I am trying to run my index.js script from outside the project directory. My project structure is as follows:

    app
      - config
          - config.js
      - public
          - index.html
      - src
          - index.js

Now when I run my src/index.js from outside my app folder, require() is able to resolve the relative paths

    const config = require(`../config/config`); 

On the other hand express.static is not able to resolve such relative paths.

    e.g. app.use(express.static("../public"));

Why do I need to use path.join and get the absolute path?

require() works off __dirname which is independent of what the current directory was when your app was loaded. It's always the directory where the module is located in, so it is consistent.

express.static() when used with relative paths uses the directory that the main app was launched form, so if you use relative paths, its behavior varies depending upon how you launch the app.

From the express doc for serving static files :

However, the path that you provide to the express.static function is relative to the directory from where you launch your node process. If you run the express app from another directory, it's safer to use the absolute path of the directory that you want to serve

So, if you want the directory to be module relative, you have to manually combine your path with __dirname to make a full path, as you have discovered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM