简体   繁体   中英

how to access parent module data in child file in node.js

my file are like avilabele this sturucture.

在此处输入图片说明

sample.js is root file and test.js is avilable in xx folder.

sample.js

    var name={
   h:14
}
module.exports=name;

test.js

var name=require('./sample.js')
console.log(name.h);

when a run test.js code using command prompt :

node test.js

it gives error like :

Cannot find module './sample.js'

var name=require('../sample.js')
console.log(name.h);

You are requiring module from the parent directory with ".."

When you require a file with a relative path, it is relative to the file doing the require (see here ). In test.js , require('./sample.js') will look for /path/to/xx/sample.js . Use require('../sample.js') since it is in the parent folder of test.js .

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