
Let's say you are issuing a Node.js command can something like this is being returned.
Error: Cannot find module 'winston'
Require stack:
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:1144:15)
at Function.Module._load (node:internal/modules/cjs/loader:985:27)
at Module.require (node:internal/modules/cjs/loader:1235:19)
at require (node:internal/modules/helpers:176:18)
at Module._compile (node:internal/modules/cjs/loader:1376:14)
at Module._compile (/usr/local/bin/node-v20.10.0-linux-x64/lib/node_modules/winston/node_modules/pirates/lib/index.js:117:24)
at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
at Object.newLoader [as .ts] (/usr/local/bin/node-v20.10.0-linux-x64/lib/node_modules/winston/node_modules/pirates/lib/index.js:121:7)
at Module.load (node:internal/modules/cjs/loader:1207:32) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'/home/john.doe/foo/bar.txt',
'/usr/local/bin/node-v20.10.0-linux-x64/lib/node_modules/winston/dist/loader.js',
'/usr/local/bin/node-v20.10.0-linux-x64/lib/node_modules/winston/dist/cli.js'
]
In this example the "winston" module cannot be found. Let's first use the npm list command to see if the module is installed in our present working directory.
]$ npm list
/home/john.doe/poc
└── (empty
And the npm list command with the -g or --global flag to see if the package is installed in the lib/node_modules of your Node.js installation (on a Linux system).
]$ npm list --global
/usr/local/bin/node-v20.10.0-linux-x64/lib
├── winston@3.17.0
├── corepack@0.22.0
└── npm@10.2.3
If the module is not installed in your present working directory or globally, then the fix is easy. Use npm install to install the package, either locally or globally.
If the module is installed globally, then you can include the full path to the module in the node_modules directory.
const { createLogger, format, transports } = require(`/usr/local/bin/node-v23.7.0-linux-x64/lib/node_modules/winston`)
Better yet, you can use execSync to get the full path to your global node_modules directory.
const { execSync } = require("child_process");
const root = execSync("npm root -g").toString().trim()
const { createLogger, format, transports } = require(`${root}/winston`)
If the module is installed globally but you still get the error, it may be the case that the node_modules directory is missing in your present working directory. This is somewhat common when pulling down a Node.js project from GitHub since the .gitignore file often ignores the node_modules directory. In this scenario, running the npm install in your present working directory (assuming you have a package.json file in your present working directory) can be the easy fix for this install.
npm install
Did you find this article helpful?
If so, consider buying me a coffee over at