简体   繁体   English

是否可以使 node 命令看到与指定位置不同的位置的 node_modules 文件夹?

[英]Is it possible to make the node command see a node_modules folder on a different location than the specified one?

I know I can install Node.js libraries with the command npm from the command line... So, if I type:我知道我可以从命令行使用命令npm安装 Node.js 库...所以,如果我输入:

npm install mylibrary

It'll create a node_modules folder on my current location and it'll install mylibrary (if it exists on npm)... Let's say that I create a Node.js code using it as the following:它将在我当前的位置创建一个node_modules文件夹,并将安装mylibrary (如果它存在于 npm 上)...假设我使用它创建了一个 Node.js 代码,如下所示:

const mylibrary = require('mylibrary')
mylibrary.doSomething()

Since I've installed this library on my current folder with the last command, this node.js script will work only if I save it on a file on my terminal current location as well.由于我使用最后一个命令在当前文件夹中安装了这个库,因此只有当我将它保存在终端当前位置的文件中时,这个 node.js 脚本才能工作。 If I name this file as file.js , I can execute it with:如果我将此文件命名为file.js ,则可以使用以下命令执行它:

node file.js

Well, my problem is that I have a very specific case where the node_modules folder cannot exist in the same location that my file.js .好了,我的问题是,我有一个非常特殊的情况下文件夹不能在同一位置,我的存在node_modules file.js Also, I'd like to avoid having to install mylibrary globally.另外,我想避免在全球范围内安装mylibrary Is there any way of defining as a parameter the path that the command node will search for the node_modules folder?有没有办法将命令node搜索node_modules文件夹的路径定义为参数? I've checked node --help and it seems there's a lot of options, but I didn't manage to make it work.我检查了node --help ,似乎有很多选项,但我没有设法让它工作。 Is it possible to do?有可能吗? Can I use a node_modules folder that's neither the one of my file.js path or a global installed library?我可以使用node_modules文件夹的既不是我的一个file.js路径或全球安装库?

You can have a link for the node_modules folder.您可以拥有 node_modules 文件夹的链接。 For example, to create the symbolink link in Linux do this:例如,要在 Linux 中创建符号链接,请执行以下操作:

cd /path/to/script/folder
ln -s /path/to/where/you/can/have/node_modules node_modules

If you can't have the link, use the full path to the node_modules folder in the require, for example:如果您没有链接,请使用 require 中 node_modules 文件夹的完整路径,例如:

const mylibrary = require('/path/to/node_modules/mylibrary')

Also, you can solve the problem by using the NODE_PATH environment variable, set it like this另外,您可以通过使用NODE_PATH环境变量来解决问题,像这样设置

export NODE_PATH=/path/to/node_modules

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

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