Node: How to run a globally installed package with npx

You can tell npm to install a package globally with npm -g install @puppeteer/browsers. However, it seems that its not possible that npx can run commands from global packages without referencing the global package path.

Example

Installing @puppeteer/browsers globally:

$ npm -g install @puppeteer/browsers

The globally installed package @puppeteer/browsers can not be access via npx:

$ npx --no-install @puppeteer/browsers

npm ERR! canceled # Error message when package is not installed

But it is installed globally:

$ npm list -g
/usr/lib
+-- @puppeteer/browsers@1.7.0
+-- corepack@0.17.1
+-- npm@9.6.3

Appending the global path works instead:

$ npx -- /usr/lib/node_modules/@puppeteer/browsers

@puppeteer/browsers <command> # Manual from the package

Use case

Here is an example for a Docker image, where a testing chrome and chromedriver is installed with a global npm package. Since there is no local project it was more useful to install the package in a global context.

RUN npm -g install @puppeteer/browsers \
  && npx -- /usr/lib/node_modules/@puppeteer/browsers install chrome@116.0.5845.96 \
  && ln -s /chrome/linux-116.0.5845.96/chrome-linux64/chrome /usr/local/bin/chrome \
  && npx -- /usr/lib/node_modules/@puppeteer/browsers install chromedriver@116.0.5845.96 \
  && ln -s /chromedriver/linux-116.0.5845.96/chromedriver-linux64/chromedriver /usr/local/bin/chromedriver
Emanuel 8 months ago