简体   繁体   中英

Nodejs can't find includes when running from relative path

I have nodejs code in the_second_folder but I want to run it from the root folder. When I run the code from the_second_folder I get no errors, but when I run the code from the root folder nodejs crashes because of includes. Here is the code:

require('rootpath')(); //does not work

var file_to_include = "file.js";
eval(fs.readFileSync(file_to_include)+'');

This only works when I run the code from the_second_folder (where it is) but fails when running from the root folder (-1 in the folder tree). The error is precisely about the inclusion of file_to_include

What I'd like to know is how can I run the node script in a relative folder scope even when called from root folder.

EDIT

file_to_include ABSOLUTE_PATH
Error: ENOENT, no such file or directory 'file_to_include.js'
...
at Object.<anonymous> (/root/the_second_folder/socket.io/lib/client.js:3:9)
...
at Object.<anonymous> (/root/the_second_folder/socket.io/lib/index.js:12:14)

Now the error happens in socket.io... any idea on this?

You can use the global __dirname , which returns the directory of the current script.

You can then do something like:

var file_to_include = "file.js";
eval(fs.readFileSync(path.join(__dirname,file_to_include))+'');

But may i ask why you are eval() ing a JS file instead of just require() ing it?

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