Tell me what's wrong - there are two files, server.js and config.json, both in the same folder.

It is written in server.js:

var config = require('config'); 

When I run server.js, I get the error Error: Cannot find module 'config'

But I will prescribe this:

 var config = require('./config'); 

It works, but I need the first option as there are subfolders where I need to use the config, what could be wrong?

    4 answers 4

    The first option require('config') indicates the use of connected libraries, they have a global scope.

    The second option require('./config') has ./ , which says to use the current folder and you can specify a file. Regarding the current folder, you can move deep into the folders require('./test/test') You can also move up one nesting level using ../ , for example. if you create a child folder myfolder , inside it use require('./../config')

      The easiest option:

       require.main.require('./config') 

      This method searches for the module config.js, located in the same directory as the main module.

      In more complex cases, you can use the rfr library (this is a separate library, you can download it via npm install rfr ):

       var rfr = require('rfr'); rfr('config'); 

      This library searches for modules with respect to the folder that is 2 levels higher than where it was installed.

      For simple projects, this will be enough, but if you are writing a library, you need to remember to add rfr to bundledDependencies so that it will be automatically placed in the folder you need when your library is downloaded.


      But I would still recommend using relative paths. Why? Because IDE. If you use IDE, then it most likely simply does not understand what kind of module you are loading in a non-standard way.

      Relative paths work in any IDE that support modules.

        If for some reason you do not want to write "./*", then you need to create a node_modules folder and put a folder with your module there, this is a feature of the require module, by default it searches for files in the node_modules folders, first from the script launch directory, then It seems to be checked by the standard Node.JS libraries. and mine correct config load so

        var config = require ('config.json');

          So what exactly is the problem? "./" is the path to the same directory where the script is located. So you have config.js and server.js on the same level. If another script is in a different folder, then you just have to set the relative path to config.js

          That's all.

          • If you read the question more closely, you would see that the author knows about relative paths - and wants to avoid them. - Pavel Mayorov