Manoj Muduli Manoj Muduli - 18 days ago 6
Node.js Question

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

my file are like avilabele this sturucture.

enter image description here

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'

Answer

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.