nodeJS require.paths resolve problem - javascript

I am trying to require a file relatively and mysteriously the following is happening
This works well which points to /Users/marcos/Desktop/Taper/lib/utils.js
myPath = "/Users/marcos/Desktop/Taper/lib/./utils";
require(myPath);
This doesn't but it should point to exactly the same file:
require.paths.unshift("/Users/marcos/Desktop/Taper/lib")
require("./utils"); //Doesn't work with './'
require("utils"); //Works Fine
Anyone knows why I can't still use ./ in this case for loading the path since
require("path").resolve("/Users/marcos/Desktop/Taper/lib", "./utils")
results in:
"/Users/marcos/Desktop/Taper/lib/utils"
anyway?
Thanks in advance

UPDATED:
From the documentation:
A module prefixed with '/' is an absolute path to the file. For
example, require('/home/marco/foo.js') will load the file at
/home/marco/foo.js.
A module prefixed with './' is relative to the file calling require().
That is, circle.js must be in the same directory as foo.js for
require('./circle') to find it.
Without a leading '/' or './' to indicate a file, the module is either
a "core module" or is loaded from a node_modules folder.
If the given path does not exist, require() will throw an Error with
its code property set to 'MODULE_NOT_FOUND'.
Here’s the original answer, which refers to require.paths (which is no longer supported):
From the documentation:
In node, require.paths is an array of strings that represent paths to be searched for modules when they are not prefixed with '/', './', or '../'.
(emphasis mine)

You can pass that using NODE_PATH
Example:
NODE_PATH=`pwd` node app.js

I created a new node module called rekuire.
It allows you to "require" without using relative paths.
It's a big time saver when it comes to testing/refactoring.
https://npmjs.org/package/rekuire

Related

Require in react can't resolve path

I'm trying to use tracking-js library in my project I'm using react but I dont know if I'm doing anything wrong but keep showing that the module is not found, I already check my package.json and the module install. So this is how I require the module:
const tracking = require("tracking");
what am I doing wrong?
For node, including node-based build tools, first make sure that the module is present. Keep in mind that require does not care about the package.json of your app, only about the module files being present.
Check if node_modules/tracking is present.
Make sure the "main" JS file can be found. If there's a node_modules/tracking/package.json file, see if it has a main property and if the file it references exists. If there is no main property, make sure there's an index.js in the root of the module directory.
If all this is fine and you're getting the module not found error at runtime in client-side JavaScript, then your bundling config may be incorrect, and your webpack/browserify/whatever config will have to be scrutinized for bugs.

what does "./" path specification means? [duplicate]

This question already has answers here:
What does "./" (dot slash) refer to in terms of an HTML file path location?
(12 answers)
Closed 8 years ago.
I have been reading through RequireJS
i dont get the difference between
define(["./cart", "./inventory"], function(cart, inventory) {...}
and
define(["cart", "inventory"], function(cart, inventory) {...}
what difference does the "./" makes?? and what alternative do we have to do , to use dependency paths without "./" ?
Generally speaking, the presence of ., .. and / in module names in RequireJS has the same meaning as for HTTP paths.
The presence of ./ in a dependency tells RequireJS to start its search from the current directory. It is extremely useful if what you want is use a module which you know is located in the same directory as the one that needs it. Let's say moduleA needs moduleB and both are in the same directory then moduleA can just require "./moduleB". One advantage of doing this is that you then don't have to worry about where the modules are stored. If you move them around but they are always together in the same directory then moduleA will always find moduleB.
Another thing is that if you require("moduleX") and there are multiple modules named moduleX available, which module are you going to get? Relative paths clarify which one you are going to get.
You ask how you can get rid of the ./ First, I'd ask do you really want to get rid of it? In the scenario I gave where two modules are in the same directory and this relation is meant to be stable, then it does not make sense to get rid of ./. It actually helps people reading the code. If what you are requiring is something like jQuery, which happens to be located in the same directory as another module at some moment but could legitimately be installed somewhere else, and which you would conceivably want to be unique for a given application, then it makes sense to have it be at a global well-known location. To do this, you use paths in your requirejs configuration, like:
paths: {
'jquery': 'external/jquery-1.9.1'
}
This is an actual piece of code part of an actual application. No matter which module wants jquery, it just issues require("jquery"). It does not have to worry about were jquery is located relative to itself. You can specify a path like this for any module you like, not just jQuery. If jQuery moves to a different location in the future or you want to serve it from a CDN, then this mapping in the snippet above is edited, but require("jquery") still works.
In context of your code, it means define cart in same directory as the current executing script.
The alternative is to use absolute paths:
/var/www/site/cart
as:
define(["/var/www/site/cart", "/var/www/site/inventory"], function(cart, inventory) {...}
Wikipedia
define(["./cart", "./inventory"], function(cart, inventory) {...}
it search specific file in current directory in filesystem
define(["cart", "inventory"], function(cart, inventory) {...}
it search specific file in root directory in filesystem
./ is refers to the current directory, to get the module currently in the same directory as the script. No ./ refers to the node path, where native and installed modules go (e.g.: net, fs, and anything use install via npm) Using an absolute path can get anywhere in the filesystem (/i/like/node/js/modules.js)
'/' refers to the root directory and
'./' refers to the current directory
define(["./cart", "./inventory"] : This will refer cart in the current directory where script is being executed.
./ means that you'll stay in the same directory.

Nodejs get directory of `required` module

Is it possible to determine the directory where required scripts come from?
My ultimate goal is to...
// return the directory where `mysql` module is found
var mysqldir = requiredir('mysql')
if(fs.existsSync(mysqldir+"/README.md")){
console.log(fs.readFileSync(mysqldir+"/README.md").toString())
}
So I can have a handy reference for all these modules, and hopefully people in the enlightened future, will include module docs/cheatsheets intended to be accessed in this manner
required.resolve(...) may be what you're looking for:
function requiredir(id) {
return path.dirname(require.resolve(id));
}
Though, this will follow the main setting:
> requiredir('grunt')
.../node_modules/grunt/lib/
(Update: Documentation for the API isn't available anymore, so its use likely isn't supported.) Another option may be to use npm's view, though this is limited to registered packages:
npm.load({}, function (err) {
npm.commands.view(['mysql', 'readme'], true, function (err, readme) {
console.log(readme);
});
});
If you want to determine the absolute path of a module you can use require.resolve('module')
http://nodejs.org/api/globals.html#globals_require_resolve
You can extract the folder path by a regular expression
If you'd like to know programmatically, the module main directory which nodejs is using, this works
require.resolve('module_name').replace(/(.*node_modules.)(.*?)(\/)(.*)/, `$1$2`)
Example
For example, if you want to know where is the module main directory of module jquery which you're using in your nodejs code, the first part
require.resolve('jquery')
returns (in my case)
/home/jfolpf/autocosts/node_modules/jquery/dist/jquery.js
Pay attention that jquery.js is not stored in the module main directory; nonetheless
require.resolve('jquery').replace(/(.*node_modules.)(.*?)(\/)(.*)/, `$1$2`)
returns
/home/jfolpf/autocosts/node_modules/jquery
This takes into account that to resolve a module's path, node always seeks recursively for the folder named node_modules, as can be seen in documentation.

node.js require relative paths

I have node.js modules in several directories because I am following MVC pattern. I am in need to call require to several modules which are located outside current directory. How can I do that?
/app/controller/c1.js
...
/app/model/m1.js
...
/app/view/v1.js
...
/app/view/v2.js
// this works
require('./v2');
// these doesn't work
require('../model/m1.js');
require('~/model/m1.js');
...
Why is that so?
For modules in other directories, use the format:
testAuth =require('./public/javascripts/test.js'),
//in case the test.js is in the public/javascripts directory (I am using Linux)
If you skip the '.js' extension, node should look for .js first before .json etc.
hope it helps.
check out this project
https://github.com/nadav-dav/rekuire
it allows you to use "require" without the relative paths, just stating the file/class name

In Node.js how can I tell the path of `this` module?

In a Node.js module I would like to open a file--i.e, with fs.readFile()--that is contained in the same directory as my module. By which I mean it is in the same directory as the ./node_modules/<module_name>/index.js file.
It looks like all relative path operations which are performed by the fs module take place relative to the directory in which Node.js is started. As such, I think I need to know how to get the path of the current Node.js module which is executing.
Thanks.
As david van brink mentioned in the comments, the correct solution is to use __dirname. This global variable will return the path of the currently executing script (i.e. you might need to use ../ to reach the root of your module).
For example:
var path = require("path");
require(path.join(__dirname, '/models'));
Just to save someone from a headache.

Categories

Resources