Programing

NodeJS는 글로벌 모듈 / 패키지를 필요로합니다

crosscheck 2020. 6. 28. 18:34
반응형

NodeJS는 글로벌 모듈 / 패키지를 필요로합니다


전 세계적으로 설치 한 다음 다음 foreverforever-monitor같이 사용하려고합니다 .

npm install -g forever forever-monitor

일반적인 출력과 파일을 전역 경로로 복사하는 작업도 보지만 시도 require("forever");하면 모듈을 찾을 수 없다는 오류가 발생합니다.

노드와 npm의 최신 버전을 사용하고 있으며 전역 및 로컬 설치에서 npm의 변경 사항에 대해 이미 알고 있지만 모든 프로젝트에 로컬을 설치하고 싶지 않으며 플랫폼이 아닌 플랫폼에서 작업하고 있습니다. 't 지원 link하므로 npm link설치 전역 후 나를 위해 할 수 없습니다.

내 질문은 : 전 세계적으로 설치된 패키지를 요구할 수없는 이유는 무엇입니까? 기능입니까, 버그입니까? 아니면 내가 잘못하고 있습니까?

추신 : 그냥 명확하게하기 위해 : 로컬로 설치하고 싶지 않습니다.


Node.js에서 require는 전역 모듈이 설치된 폴더를 찾지 않습니다.

NODE_PATH 환경 변수를 설정하여이 문제를 해결할 수 있습니다. 리눅스에서 이것은 :

export NODE_PATH=/usr/lib/node_modules

참고 : 이것은 전역 모듈이 실제로 설치된 위치에 따라 다릅니다.

전역 폴더에서로드를 참조하십시오 .


전역으로 패키지를 설치 한 후에는 로컬 프로젝트를 전역 패키지와 연결해야합니다

npm install express -g
cd ~/mynodeproject/
npm link express  

여기를 참조 하십시오


네크로 맨시에 사과하지만 전 세계적으로 설치된 모듈에 대한 하드 코딩 된 경로를 지정할 수 있습니다.

var pg = require("/usr/local/lib/node_modules/pg");

이것은 완벽하지는 않지만 Unity3d가 프로젝트 디렉토리에 포함 된 모든 자바 스크립트를 "컴파일"하려고한다고 생각하면 실제로 패키지를 설치할 수 없습니다.


나는 이것이 오래된 질문이라는 것을 알고 있지만 semverpreinstall스크립트에서 버전 확인을 시도 할 때이 문제가 발생 했습니다 package.json. 설치된 로컬 모듈에 의존 할 수 없다는 것을 알았으므로 semver전역 node_modules폴더 에서 요구하는 데 사용 npm했습니다 (내가 아는 것처럼).

function requireGlobal(packageName) {
  var childProcess = require('child_process');
  var path = require('path');
  var fs = require('fs');

  var globalNodeModules = childProcess.execSync('npm root -g').toString().trim();
  var packageDir = path.join(globalNodeModules, packageName);
  if (!fs.existsSync(packageDir))
    packageDir = path.join(globalNodeModules, 'npm/node_modules', packageName); //find package required by old npm

  if (!fs.existsSync(packageDir))
    throw new Error('Cannot find global module \'' + packageName + '\'');

  var packageMeta = JSON.parse(fs.readFileSync(path.join(packageDir, 'package.json')).toString());
  var main = path.join(packageDir, packageMeta.main);

  return require(main);
}

사용하기 위해 특별한 모듈을 설치할 필요가 없기 때문에이 방법이 마음에 듭니다.

프로젝트 NODE_PATH를 실행하기 전에 추가 구성 / 설정을 요구하지 않고 다른 사람의 컴퓨터 에서이 작업을 수행하기를 원했기 때문에 다른 사람들이 제안한 솔루션을 사용 하지 않았습니다 npm install.

이 코딩 방법, 단지 최상위 모듈 (사용하여 설치 찾을 보장 npm install -g ...) 또는에 필요한 모듈 npm(로 나열 dependencies: 여기 https://github.com/npm/npm/blob/master/package.json ). 최신 버전의 NPM을 사용하는 경우 node_modules폴더에 대한 구조가 더 편하기 때문에 전 세계적으로 설치된 다른 패키지의 종속성을 찾을 수 있습니다.

이것이 누군가에게 유용하기를 바랍니다.


패키지 requireg사용 하여이 문제를 해결할 수 있습니다 .

var forever = require('requireg')('forever')

트릭을 할 것입니다.

또한 global-npmglobal을 사용하는 것과 관련된 다른 모듈이 npm있지만 짧은 코드 를보고 기술이 어떻게 작동하는지 확인할 수 있습니다.


당으로 문서 , Node.js를 기본적으로 다음 위치에서 검색합니다 :

  1. Path specified in the NODE_PATH environment variable.

    Note: NODE_PATH environment variable is set to a colon-delimited list of absolute paths.

  2. Current node_modules folder. (local)

  3. $HOME/.node_modules (global)

    Note: $HOME is the user's home directory.

  4. $HOME/.node_libraries (global)
  5. $PREFIX/lib/node (global)

    Note: $PREFIX is Node.js's configured node_prefix.

    To check the current value of node_prefix, run:

    node -p process.config.variables.node_prefix
    

    Note: Prefix corresponds to --prefix param during build and it's relative to process.execPath. Not to confuse with value from the npm config get prefix command.source

If the given module can't be found, that means it is not present in one of the above locations.

Location of global root folder where modules are installed can be printed by: npm root -g (by default the path is computed at run-time unless overridden in npmrc file).

Solution

You can try the following workarounds:

  • Specify your global module location in NODE_PATH environment variable. E.g.

    echo 'require("forever")' | NODE_PATH="$(npm root -g):$NODE_PATH" node
    

    To test and print the value of NODE_PATH, run:

    echo 'console.log(process.env.NODE_PATH); require("forever")' | NODE_PATH="$(npm root -g):$NODE_PATH" node 
    
  • For more permanent solution, link your $HOME/.node_modules global user folder to point to the root folder, by running this command:

    ln -vs "$(npm root -g)" "$HOME"/.node_modules
    

    Then re-test it via: echo 'require("forever")' | node command.

  • Temporary change the current folder to where the extension has been installed globally, before invoking the script. E.g.

    npm install -g forever
    cd "$(npm root -g)"
    echo 'require("forever")' | node
    cd -
    
  • Configure global installation destination in npm userconfig file (see: npm help 5 npmrc) or by userconfig param (--prefix).

    To display the current config, run: npm config list.

    To edit the current config, run: npm config edit.

  • Specify the full path of node modules location when calling require(). E.g.

    require("/path/to/sub/module")
    
  • Install the package to custom location, e.g.

    npm install forever -g --prefix "$HOME"/.node_modules
    

    However, the installation will go under ~/.node_modules/lib/node_modules/, so the location still needs to be added.

    See: npm local install package to custom location

  • Create a symlink in the current folder from the location of the global package. E.g.

    npm link forever
    

For CLI utilities that depend on big modules, like puppeteer, I like to spawn a npm root -g and use it to require the global module.

try {
  const root = require('child_process').execSync('npm root -g').toString().trim()
  var puppeteer = require(root + '/puppeteer')
} catch (err) {
  console.error(`Install puppeteer globally first with: npm install -g puppeteer`)
  process.exit(1)
}

You can put this line in your .profile file:

export NODE_PATH="$(npm config get prefix)/lib/node_modules"

This will make node use the global path.

참고URL : https://stackoverflow.com/questions/15636367/nodejs-require-a-global-module-package

반응형