Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Require a node_module from within a subfolder

So I have some node.js files

/folder/app.js
/folder/node_modules/moduleIwanttoload
/folder/subfolder/file.js

how do I require moduleIwanttoload from file.js?

like image 982
Jim Jones Avatar asked Jul 20 '14 20:07

Jim Jones


People also ask

For what require () is used in Node JS?

In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.

How do I require a module?

You can think of the require module as the command and the module module as the organizer of all required modules. Requiring a module in Node isn't that complicated of a concept. const config = require('/path/to/file'); The main object exported by the require module is a function (as used in the above example).

How do you use require in JavaScript?

To include the Require. js file, you need to add the script tag in the html file. Within the script tag, add the data-main attribute to load the module. This can be taken as the main entry point to your application.

Which object is used to manage the cache of required modules?

Module. _load performs the loading of new modules and manages the cache. On a file loading request, it will first check the file in cache. If module is not found in the cache, this will create a new base module instance for the required file.


2 Answers

you can use subfolder files like this into app.js

var file = require('./subfolder/file.js');

and in the folder of node-modules you can just use it like

var moduleIwanttoload = require("moduleIwanttoload");
like image 186
Muhammad Ali Avatar answered Oct 14 '22 21:10

Muhammad Ali


If the module you want to load is a dependency contained in "node_modules" you can simply use

require("moduleIwanttoload")

Node JS will trace the directory tree down to the first folder in which it finds a "node_modules" directory and looks for the given dependency in it.

like image 43
thertweck Avatar answered Oct 14 '22 20:10

thertweck