Search code examples
node.jspg

Error: Cannot find module 'pg', after running npm install pg


Using VSCode. Installed latest Node.js (first time user) for Windows, and the desired modules, one of which was 'pg' (npm install pg)

At the top of my script I have this: const pg = require('pg');

When i attempt to debug, I get this error when it hits that line:

Exception has occurred: Error
Error: Cannot find module 'pg'
at Function.Module._resolveFilename (module.js:547:15)
at Function.Module._load (module.js:474:25)
at Module.require (module.js:596:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (c:\EBI\Work\Node-pg-log\get_pg_log.js:3:12)
at Module._compile (module.js:649:14)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)

Is there something else I need to install or set up? Debugging is in place.


Solution

  • This usually happens when node_modules/ folder is located in some sub-directory. Like

    /app
    ----index.js
    ----/libs
    --------/node_modules/
    

    You want a directory structure like

    /app
    ----index.js
    ----node_modules/
    

    Where node_modules folder is either in the current directory or in some upper level directory