我怎么知道模块是从磁盘上的哪个位置加载的?
How do I know where on disk a module is being loaded from?
根据 npm list
,我有一个文件系统中不存在的模块 @vendorname/functions
$ npm ls @vendorname/functions
serverless-commerce@1.0.0 C:\Users\mikem\OneDrive\Documents\myapp\myapp
`-- (empty)
根据演示文件也不存在:
$ node
> require("@vendorname/functions")
{ Error: Cannot find module '@vendorname/functions'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:580:15)
at Function.Module._load (internal/modules/cjs/loader.js:506:25)
at Module.require (internal/modules/cjs/loader.js:636:17)
at require (internal/modules/cjs/helpers.js:20:18) code: 'MODULE_NOT_FOUND' }
但是我在父文件夹 C:\Users\mikem\OneDrive\Documents\myapp\myapp
中有一个使用该模块的软件并且它可以工作:
let vendornameFunctions = require("@vendorname/functions"),
log(`>>> MYSTERY FILE IS BEING IMPORTED ${JSON.dumps(vendornameFunctions, null, 2)}`);
Returns:
>>> MYSTERY FILE IS BEING IMPORTED {
"events": {},
"queues": {},
"tables": {},
"html": {},
"json": {},
"css": {},
"js": {},
"text": {},
"xml": {}
}
我可以可靠地复制这种行为。 如何确定模块从磁盘上的哪个位置加载?
您可以使用 require.resolve
获取模块的路径。
console.log(require.resolve("@vendorname/functions"));
根据 npm list
@vendorname/functions
$ npm ls @vendorname/functions
serverless-commerce@1.0.0 C:\Users\mikem\OneDrive\Documents\myapp\myapp
`-- (empty)
根据演示文件也不存在:
$ node
> require("@vendorname/functions")
{ Error: Cannot find module '@vendorname/functions'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:580:15)
at Function.Module._load (internal/modules/cjs/loader.js:506:25)
at Module.require (internal/modules/cjs/loader.js:636:17)
at require (internal/modules/cjs/helpers.js:20:18) code: 'MODULE_NOT_FOUND' }
但是我在父文件夹 C:\Users\mikem\OneDrive\Documents\myapp\myapp
中有一个使用该模块的软件并且它可以工作:
let vendornameFunctions = require("@vendorname/functions"),
log(`>>> MYSTERY FILE IS BEING IMPORTED ${JSON.dumps(vendornameFunctions, null, 2)}`);
Returns:
>>> MYSTERY FILE IS BEING IMPORTED {
"events": {},
"queues": {},
"tables": {},
"html": {},
"json": {},
"css": {},
"js": {},
"text": {},
"xml": {}
}
我可以可靠地复制这种行为。 如何确定模块从磁盘上的哪个位置加载?
您可以使用 require.resolve
获取模块的路径。
console.log(require.resolve("@vendorname/functions"));