Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs - what to use instead of require.paths?

Tags:

node.js

Recent node docs say that modifying require.paths is bad practice. What should I do instead?

like image 402
nornagon Avatar asked Feb 27 '11 04:02

nornagon


People also ask

Can I use import in Node instead of require?

You can now start using modern ES Import/Export statements in your Node apps without the need for a tool such as Babel. As always, if you have any questions, feel free to leave a comment.

Should I use import or require?

One of the major differences between require() and import() is that require() can be called from anywhere inside the program whereas import() cannot be called conditionally, it always runs at the beginning of the file. To use the require() statement, a module must be saved with . js extension as opposed to .

For what require () is used in Node js?

Node. js follows the CommonJS module system, and the built-in require function is the easiest way to include modules that exist in separate files. The basic functionality of require is that it reads a JavaScript file, executes the file, and then proceeds to return the exports object.

How do you use require in JavaScript without Node?

A module loader called RequireJS exists for in-browser use without the use of Node. js or Rhino. The data-main attribute will point to your main script where you can load the rest of your scripts using: require(["helper/util"], function(util) { //This function is called when scripts/helper/util.


3 Answers

I believe the concern is that it can be repeatedly modified at run time, rather than just set. That could obviously be confusing and causes some quite bizarre bugs. Also, if individual packages modify the path the results are applied globally, which is really bad and goes against the modular nature of node.

If you have several library paths of your own, the best solution is to set the NODE_PATH environment variable before launching node. Node then picks this up when it's launched and applies it automatically.

like image 134
leebriggs Avatar answered Sep 24 '22 09:09

leebriggs


I keep the related models in the same dir or a sub dir and load using:

var x = require('./mod/x');

In case it's an external module, I install it using npm that puts the module correctly in NODE_PATH.

I've never changed require.paths.

like image 22
Carlosedp Avatar answered Sep 22 '22 09:09

Carlosedp


have a look at https://github.com/patrick-steele-idem/app-module-path-node; you can add a directory to the require statements in the top level, without influencing the paths of sub-modules.

like image 29
flow Avatar answered Sep 23 '22 09:09

flow