Module not found error in node.js

according to the folder structure you mentioned in the question, you have to try

require('../utils/utils.js')

This is the case if you have your project folder structured like

  • proj
    • src
      • utils
        • utils.js
      • main
        • main.js

and you are doing node main.js

To comment on the details provided in your question.

  1. please dont use require(c:/demo/proj/src/utils/utils.js); as you are tried out. imagine like you are exporting the proj folder with your project files then the mentioned require will be an error.

  2. Also the folder structure could be made to something like

    • proj
      • src
        • utils - utils.js
      • main.js
      • package.json

so that you keep the main file in root of project folder. and require the utils.js like

 require('./src/utils/utils.js')

UPDATE

As far as ican see from the updated error message. Its still the issue with the path of 'utils.js' in require. From your updated folder structre It seems that main.js is in same level as proj folder, see that the proposed folder structure had main.js and src folder in same level inside proj folder.

Even that was a suggestion that I made as you were following a folder structure that dint make any sense. Simply require('../utils/utils.js') would have solved your issue without even altering the folder structure you mentioned in the beginning.


First of all, check your current folder. Are you in the right folder?

if(yes) then this answer is not for you can leave and go further

if(not sure || No)

cd "your folder name." 
node "your file name.js."

Use: require('./utils.js');. This is the correct way to require a module from a file which is located in required module's folder.

You must provide a relative or absolute path I guess utils.js is not in your root so require('/utils.js'); is not the right path.

Example:

Imagine you have two files utils.js and main.js in the same folder. The content of utils.js is:

utils.js

exports.foo = function () {
    console.log('foo');
};

In order to call foo from utils.js in main.js you should use:

main.js

require('./utils.js').foo();