简体   繁体   中英

Relative path not resolved in nodejs

I create a module named core that has core functionality of the project. I also created a services project that used the core project in nodejs. This core module to be included as node_modules dependency (package.json) in service-app.

my service app call the core app and core app uses relative path:


//core-app -> logger.js

const loggerConfig = require('../../configs/logger-config.json');

When service app start then it require core-app -> logger.js

const logger = require('core');

than it prompt error

Error: Cannot find module '../../configs/logger-config.json

Here ../../configs/logger-config.json is correct and it sometimes runnig on other system properly.

Now, I replace the relative path to,

//core-app -> logger.js
const path = require('path');
const loggerConfig = require(path.join(__dirname,'../../configs/logger-config.json'));

then it is running.

I resolved error but not sure about code standard. For reference, I checked the other node_modules library and found they also used relative in the same manner but my case it prompts an error.

__dirname gives the current directory where the thread executes in nodejs. So, in place of relative path better to use through __dirname .

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