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.
Related
Node.js path resolve system make me mad. I have
var a = '../data/data.db' path to a file but this path resolve differently depending from am I run this code from node.js directly or from test runner or from CI. Is there is a standard unified way how relative paths need to be managed in node.js?
You should use the __dirname property and path.resolve. __dirname gives you the path to the scripts location as opposed to the current execution location, and path.resolve cleans up the relative path.
var path = require('path');
var a = path.resolve(__dirname, '../data/data.db');
Your can use global variable such as __dirname which points to the directory the currently executing script resides.
I'm using the Yeoman Generator Angular Fullstack and I'd like to reuse JS code from different directories within my server directory. I'm referencing the file that has the functions I want like:
var something = require('/.path');
I get the error: "Cannot find module" in my terminal.
I tried a number of variations of the path working through all of the levels from server level down to file level where the given functions are contained. I looked at a few tutorials:
http://www.sitepoint.com/understanding-module-exports-exports-node-js/
AND
https://www.launchacademy.com/codecabulary/learn-javascript/node/modules
I clearly missed something. Each module of my nodejs has a controller with an exports.create function. All of my code for each module is contained within my exports.create function accept for other required modules. I have no problem requiring underscore or other libraries in my Node/Bower modules by the way.
To be as detailed as can be, I expected
var something = require('./directory/directory.controller.js');
var something = require('/.path');
The path you are using is likely incorrect. Probably you want to open the file called path.js contained in the same folder of the file from which you are importing it. In order to do that, you should change the import as follows :
var something = require('./path');
./path is a relative path where . stands for current directory.
/.path is an absolute path. In this case require is importing a hidden file in the root directory. I guess is not what you want.
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.
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.
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