R
R
romaro2021-04-13 15:12:19
Node.js
romaro, 2021-04-13 15:12:19

What is the best way to set paths to static files in Node?

For example, I have routes in my project:
- project/
- - routers/
- - - regRouter.js

regRouter.js has a page rendering handler:

router.get('/', function (req, res) {
    res.render('/home/nodejs/project/public/views/reg');
});


So far I see 3 options:
1) define a global variable for the project root, initialize it in the main application file and write something like:
res.render(__rootDir + 'public/views/reg');

2) use app-root-path , which will have to be imported into each route file.

3) define the NODE_PATH variable before starting the application, but for some reason it seems that this is a more fragile way.

It is important that the server can have several applications running Node.
Which option would you recommend?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lynn "Coffee Man", 2021-04-13
@romaro

What people don’t go to just not to read the documentation
https://expressjs.com/en/4x/api.html#res.render

The view argument is a string that is the file path of the view file to render. This can be an absolute path, or a path relative to the views setting.

https://expressjs.com/en/4x/api.html#app.set
views
String or Array
A directory or an array of directories for the application's views. If an array, the views are looked up in the order they occur in the array.
default value: process.cwd() + '/views'

So somewhere at the beginning of the application you need to write app.set('views', 'public/views') , and in the handler res.render('reg') .
Everything.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question