How is this node.js module getting loaded? - node.js

I have just started learning node and express and stumbled across this sample express application - https://github.com/madhums/node-express-mongoose-demo.
The server.js file loads a module named config without a relative path -
var config = require('config')
https://github.com/madhums/node-express-mongoose-demo/blob/master/server.js#L15.
What I don't understand is how the module is getting loaded. There is no module named config in node_modules. The package.json contains NODE_PATH which points to ./config folder. However, the config folder doesn't contain an index.js file.
So how does the config object gets its properties?

NODE_PATH points to super-folders that contain Node modules (which may themselves be in folders, or maybe single files).
The modules documentation says:
If the NODE_PATH environment variable is set... then node will search those paths for modules if they are not found elsewhere.
It search those paths for modules; it does not treat those paths as modules.
Therefore, require('config') loads ./config/config.js. The NODE_PATH=./config:... tells Node to look in ./config for modules, and it find successfully finds a file called config.js in that folder, which it loads as a module.

Related

how to make webpack use shared node modules in the parent directory

I want to use shared node modules which is kept in the parent directory. I have the following folder structure:
parent directory
node_modules
company
serverless.yml
handler.js
webpack.config
I have to use webpack to create packages and upload into aws-lamda. But the webpack is looking for node modules. But I am getting the following error:
Overriding the webpack directory in serverless-webpack since it uses v1 version of webpack...
cp: cannot stat 'node_modules/webpack': No such file or directory
How can I make webpack.config point to the node_modules in the parent directory?
if you read the NodeJS require documentation you are highly encouraged to use local node_modules folders even if your packages require have the same dependencies.
https://nodejs.org/api/modules.html#modules_loading_from_node_modules_folders
Alternatively your can work with NODE_PATH , notice that require will first look into local node_modules then start looking into other folders so try to delete local node_modules
If the NODE_PATH environment variable is set to a colon-delimited list of absolute paths, then Node.js will search those paths for modules if they are not found elsewhere. (Note: On Windows, NODE_PATH is delimited by semicolons instead of colons.)
Since webpack exposes many module resolving options https://webpack.github.io/docs/resolving.html
Resolving a module path
For resolving a module Resolve first gathers all search directories for modules from Webpack’s context directory. This process is similar to the node.js resolving process, but the search directories are configurable with the configuration option resolve.modulesDirectories. In addition to this the directories in the configuration option resolve.root are prepended, and directories in the configuration option resolve.fallback are appended.

node.js require function not finding module

I have a server.js file that I downloaded from someone's website. The first line is: var express=require('express');
When I try to run this server with "node server.js" I get the following error: "Cannot find module 'express'." The express module is installed in the default node install location:
C:\Users\myname\node_modules\express\
I'm able to successfully run express by executing "node express.js" from the express install location in node_modules. I also tried copying over the express folder and file into my c:\node-testing\ directory where my server.js file is located but I still get the error. Any idea what the problem might be and how to fix?
You can set the NODE_PATH environment variable to tell nodejs to search other paths for globally installed modules that are not in the project directory.
See http://nodejs.org/api/modules.html#modules_loading_from_the_global_folders for details.
On Unix installations there are some built-in default locations, but on Windows, it appears you have to set this environment variable manually to support a global location.
FYI, if you want require to load a module from the project directory, then you have to use
require("./filename");
with the ./ in front of it. That's why it didn't work when you copied it to the project directory. node makes a distinction between loading from the project directory vs. loading from the node_modules directory below and thus requires a different syntax to specify which one you want. Express.js is also not a stand-alone module because it depends on a bunch of other modules so you could not copy only it. I'd recommend using the NODE_PATH option or install express into your project directory (it will end up in a node_modules sub-directory).
Node.js will only search for modules in from the current (and parent) directories. Unlike npm, Node has no concept of "global" modules.
You need to run npm install to install your modules into the directory containing your code.

How to provide module dependencies for required script in a sibling directory

I am running a node.js script (foo.js) that requires a helper script that is located in a sibling directory.
//foo.js:
var magic = require('../util/magic');
magic.js uses a npm module express. However, the main directory of the 'program' (holding package.json and node_modules) is the folder where foo.js is located.
/program
/node_modules
/express
..
/foo.js
/package.json
/util
/magic.js
When running the program, the statement require('express') in magic.js fails - the module cannot be found.
Is there a way to make node.js load the express module from the program/node_modules directory?
I would like to avoid any of the following:
move the node_modules directory to a common parent of util and program
add a node_modules directory to util
pass in a reference of the required modules to magic.js
Appreciate your help!
You could supply a relative path instead the module name, because this is how Node.js is going to check for the modules folder if you don't specify a path:
/util/node_modules
/node_modules
Since you know where the module already exists, just do this instead:
var express = require('../program/node_modules/express');
However, you should place any files related to the module within the module itself when developing modules. If you don't, they don't get packaged with the module either when it is published, and you have this inconvenience of not being able to access dependencies specified in the package file.

How do I execute symbolic linked files in node.js?

I'm writing an application that contain a skeleton directory that would be copied to a new node project. Since I'm debugging the skeleton, I'm symlinking the file in my new folder,
so:
mainapp/skel/index.js
sampleapp/index.js -> ../mainapp/skel/index.js
sampleapp/package.json
sampleapp/node_modules/abc
index.js:
require('abc');
But running the sampleapp with:
node index.js
are not working because it seems to try to find the module in mainapp/skel/node_modules instead of sampleapp/node_modules. Any idea for a workaround?
You have two options -
Symlink node_modules directory in skel
Set NODE_PATH environment variable
export NODE_PATH=<path_to_sampleapp_node_modules>

how to define a file as a module in node.js

instead of requireing code relatively, ie starting with ./ or .., i'd like to define a module "globally". For example, take the following package structure:
/src
/index.js
/a.js
/b.js
/lib
/index.js
...
When in src/a.js or src/b.js, to require lib, I would have to do require('../lib') each time. This gets annoying when you start nesting more as you would have to manually resolve ../lib or ../../lib or ../../../lib.
I want to be able to do require('lib'). Can I do this? Or should I just use globals?
Using a non relative path to require your source files is not how node's require is intended to work! Don't try to work around this restriction by placing arbitrary code file in node_modules directory or workaround by changing the NODE_PATH environment variable.
If you want to use require without a path you should extract the required code as a node module and depend on this node module. This leads to better structured code, less complex modules, encapsulated functionality, better testability and easier code reuse.
You can include package dependencies from http or git so there is no requirement to publish node modules you use in npm. Take a look at npm dependencies for more detail.
use module.exports in the index.js file . and place it inside the node_modules folder
if relative path annoy you and you want to use lib always in your application, you can use global variable like this.
var lib = require('./lib');
global.lib = lib;
you can set lib to global variable in your entry point. after then you can access just lib.
but it's pollute global scope. so you have to use carefully.
placing your module in node_modules dont require you to include a path or relative path
EDIT:
if you place a file named package.json inside the module directory, Node will try to parse that file and look for and use the main attribute as a relative path for the entry point. For instance, if your
./myModuleDir/package.json
file looks something like the following, Node will try to load the file with the path
./myModuleDir/lib/myModule.js
:
{
"name" : "myModule",
"main" : "./lib/myModule.js"
}
If that folder does not contain a package definition file named package.json, the package entry point will assume the default value of index.js, and Node will look, in this case, for a file under the path ./myModuleDir/index.js.

Resources