简体   繁体   English

如何在node.js的子文件中访问父模块数据

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

my file are like avilabele this sturucture. 我的文件就像avilabele这样的结构。

在此处输入图片说明

sample.js is root file and test.js is avilable in xx folder. sample.js是根文件,而test.jsxx文件夹中可用。

sample.js sample.js

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

test.js test.js

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

when a run test.js code using command prompt : 当使用命令提示符运行test.js代码时:

node test.js 节点test.js

it gives error like : 它给出如下错误:

Cannot find module './sample.js' 找不到模块“ ./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 ). 当你需要使用相对路径的文件,它是相对于文件做require (见这里 )。 In test.js , require('./sample.js') will look for /path/to/xx/sample.js . test.jsrequire('./sample.js')将查找/path/to/xx/sample.js Use require('../sample.js') since it is in the parent folder of test.js . 使用require('../sample.js')因为它位于test.js的父文件夹中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM