指向node_modules文件夹中自定义缓存的符号链接

uxh89sit  于 12个月前  发布在  Node.js
关注(0)|答案(1)|浏览(100)

我正在为NodeJS编写自己的包管理器。所有已安装的软件包都存储在node-cache文件夹中,如下所示:
node-cache/ [[email protected]](https://stackoverflow.com/cdn-cgi/l/email-protection)
node-cache/ [[email protected]](https://stackoverflow.com/cdn-cgi/l/email-protection)
将包命名为package@version非常重要,这样可以在该高速缓存中存储多个版本。当向NodeJS项目添加包时,node modules文件夹将包含指向该高速缓存的符号链接,如下所示:
/node_modules/x -> /node-cache/ [[email protected]](https://stackoverflow.com/cdn-cgi/l/email-protection)
/node_modules/y -> /node-cache/ [[email protected]](https://stackoverflow.com/cdn-cgi/l/email-protection)
我得到了我的代码来做这件事,并测试了以下情况:

// project/index.js
require("x");

使用/node-cacheproject/node_modules结构,如我上面展示的示例。我还使[[email protected]](https://stackoverflow.com/cdn-cgi/l/email-protection)执行require("y"),以确保包可以在该高速缓存中正确地相互解析。
我还将env变量NODE_PATH设置为/node-cache路径,以确保模块在该高速缓存目录中解析,而不是在本地解析。当运行node index.js时,[[email protected]](https://stackoverflow.com/cdn-cgi/l/email-protection)加载得很好,并得到解决。但是[[email protected]](https://stackoverflow.com/cdn-cgi/l/email-protection)没有解决,我得到了这个错误:

node:internal/modules/cjs/loader:1078
  throw err;
  ^

Error: Cannot find module 'y'
Require stack:
- C:\Users\samal\AppData\Local\node-cache\[email protected]\index.js
- A:\Downloads\test\index.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1075:15)
    at Module._load (node:internal/modules/cjs/loader:920:27)
    at Module.require (node:internal/modules/cjs/loader:1141:19)
    at require (node:internal/modules/cjs/helpers:110:18)
    at Object.<anonymous> (C:\Users\samal\AppData\Local\node-cache\[email protected]\index.js:1:11)
    at Module._compile (node:internal/modules/cjs/loader:1254:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1308:10)
    at Module.load (node:internal/modules/cjs/loader:1117:32)
    at Module._load (node:internal/modules/cjs/loader:958:12)
    at Module.require (node:internal/modules/cjs/loader:1141:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    'C:\\Users\\samal\\AppData\\Local\\node-cache\\[email protected]\\index.js',
    'A:\\Downloads\\test\\index.js'
  ]
}

这是因为我的缓存文件名为package@version而不是package,我需要缓存同一个包的多个版本。节点正在搜索/node-cache/y作为require()'d by [[email protected]](https://stackoverflow.com/cdn-cgi/l/email-protection),但只有/node-cache/ [[email protected]](https://stackoverflow.com/cdn-cgi/l/email-protection)。删除NODE_PATH env变量会产生相同的错误。
我想知道,什么是最好的解决方案,而不强迫用户做任何额外的不必要的工作,以获得包管理器的工作,同时保持其快速速度,并使用符号链接或任何不需要文件系统副本?

jtoj6r0c

jtoj6r0c1#

解决办法其实很简单。解决方案是使用--sample-symlinks标志。例如node --preserve-symlinks index.js
这确保了符号链接是在本地解析的,而不是在该高速缓存中解析,这就是它的工作原理。

相关问题