S
S
shedy2014-02-17 19:55:58
Node.js
shedy, 2014-02-17 19:55:58

How to get application root url in node.js?

Need to get localhost/myapp url in node.js code. I can't find it anywhere on the net, please help. THX

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Q
quex, 2014-02-17
@quex

If I understand correctly, you need a path to the application file? Let's say you run the application /var/www/mysuperapp/app.js and you need to get the path to this file.
if so, then the __dirname variable is what you need. this variable is available within each file, and contains the path to the file within which it is used.
if you have one file nested in another, require is used and you need to know the root of the application (main file) everywhere, then the easiest option is to write the path of the main file to a global variable and use it in nested files

/* файл /var/www/mysuperapp.js */
global.__approot = __dirname;
require('./requires/child.js');

/* файл /var/www/requires/child.js */
console.log(__approot); // /var/www/

if you want complete control - pay attention to the module.parent property, and to the module object in general, there is a lot of information there that can be useful in many cases.

K
Konstantin Kitmanov, 2014-02-18
@k12th

See how requests are handled in node-router .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question