簡體   English   中英

如何在node.js的子文件中訪問父模塊數據

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

我的文件就像avilabele這樣的結構。

在此處輸入圖片說明

sample.js是根文件,而test.jsxx文件夾中可用。

sample.js

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

test.js

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

當使用命令提示符運行test.js代碼時:

節點test.js

它給出如下錯誤:

找不到模塊“ ./sample.js”

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

您需要父目錄中帶有“ ..”的模塊

當你需要使用相對路徑的文件,它是相對於文件做require (見這里 )。 test.jsrequire('./sample.js')將查找/path/to/xx/sample.js 使用require('../sample.js')因為它位於test.js的父文件夾中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM