gpt4 book ai didi

javascript - Node "require"语法创建模块的新引用

转载 作者:行者123 更新时间:2023-12-03 01:00:32 25 4
gpt4 key购买 nike

我有这些文件

/Controller/sub_module/conversation.js

var test = [];
function push(){
test.push(test.length);
}
module.exports = {
push,
getTest(){
return test;
}
}

/index.js(位于根目录)

require('../chatserver/Controller/sub_module/conversation').push();//push new item to test variable

然后在/Controller/index.js

const test1 = require('../Controller/sub_module/conversation').getTest();//return [0]
const test2 = require('./sub_module/conversation').getTest(); //return []

test1 和 test2 没有指向相同的引用,为什么? Node 8.11.3IDE网络 Storm Debug image

最佳答案

感谢@T.J.Crowder:https://nodejs.org/api/modules.html#modules_module_caching_caveats .

我认为所有相对路径都会转换为绝对路径以供名称缓存使用,并且在这种转换中,相对路径的未指定部分将自动小写字母。

因为该 Node 会考虑

require('./sub_module/conversation') //the unspecified part is 'Controller' will be convert to 'controller'

相同
require('../controller/sub_module/conversation')

但不同

require('../Controller/sub_module/conversation')

关于javascript - Node "require"语法创建模块的新引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52644165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com