Both these require statements appear to work the same way:
var Mypackage = require('mypackage.js');
var Mypackage require('mypackage');
Is there a difference between them?
Here is the answer:
Module.prototype.load = function(filename) {
debug('load ' + JSON.stringify(filename) +
' for module ' + JSON.stringify(this.id));
assert(!this.loaded);
this.filename = filename;
this.paths = Module._nodeModulePaths(path.dirname(filename));
var extension = path.extname(filename) || '.js';
if (!Module._extensions[extension]) extension = '.js';
Module._extensions[extension](this, filename);
this.loaded = true;
};
Node.JS looks to see if the given module is a core module. (e.g. http, fs, etc.)
Always takes the precedence in the loading modules.
If the given module is not a core module (e.g. http, fs, etc.), Node.js will then begin to search for a directory named, node_modules.
It will start in the current directory (relative to the currently-executing file in Node.JS) and then work its way up the folder hierarchy, checking each level for a node_modules folder.
Once Node.JS finds the node_modules folder, it will then attempt to load the given module either as a (.js) JavaScript file or as a named sub-directory; if it finds the named sub-directory, it will then attempt to load the file in various ways. So, for example
If you make a request to load the module, "utils" and its a directory not a .js file then:Node.JS will search a hierarchical directory for node_modules and
utils in the following ways:
./node_modules/utils.js
./node_modules/utils/index.js
./node_modules/utils/package.json
If Node.JS still can't find the file in above steps, Node.js will then start to look into the directory paths from environment variables i.e. NODE_PATH set on your machine(obviously set by Node.JS installer file if you are on windows)
Not Found in all the above steps then, prints a stack trace to stderE.g.: Error:Cannot find module 'yourfile'
For more information: link is here even the cyclic require() is explained very well.
Related
I have project A that has a config.json file in its root. The project has a dependency on external module B, calling B.setConfig('./config.json').
While inside B.setConfig(path), if I call fs.existsSync(path), it says Ok, file exists, but calling require(path) fails with Cannot find module "./config.json".
Is it possible to adjust the relative path while inside module B to make require work?
I would prefer not to call setConfig with the full path, as it makes things awkward.
I found it, eventually, that if we want to take a relative path from module A (call it remotePath), and use it within require in module B, then to get the full path inside module B we can use the following:
var path = require('path');
var fullPath = path.join(path.dirname(process.argv[1]), remotePath);
var moduleInsideA = require(localPath); // this now works
process.argv[1] gives us the module A start-up file, from which we take the directory path, and then join it with the remote relative path, which then gives us the full path.
I'm trying to access a file contained within a node dependency. Previously I was hardcoding access to this file in the form require('../../node_modules/foo/bar.png') however this path cannot be relied upon with npm v3 as the place in the node_modules folder hierarchy where a given dependency sits may change. require.resolve doesn't seem to help me as it gives the main file within the dependency rather than just the folder of the dependency.
Assuming you're writing both modules you can use __dirname from inside the dependency to get the path the module is running from:
//foo/index.js
module.exports.root = __dirname;
Then use that to serve the files:
//server.js
var assets = require('foo');
fs.readFile(assets.root + '/bar.png', function(){/*whatever*/});
My solution is by using https://www.npmjs.com/package/dive and assert every files.
dive(directory[, options], action[, complete]);
A common solution I have found on github in various open source projects is to use findup/findup-sync, ie
var findup = require('findup-sync');
var filePath = findup('node_modules/foo/bar.png');
I am using node v0.12.5 with nwjs and I have defined my own custom module inside of my project so that I can modularise my project (obviously).
I am trying to call my module from another module in my project but every time I attempt to require it I get the error could not find module 'uploader'.
My uploader module is currently very simple and looks like:
function ping_server(dns, cb) {
require('dns').lookup(dns, function(err) {
if (err && err.code == "ENOTFOUND") {
cb(false);
} else {
cb(true);
}
})
}
function upload_files()
{
}
module.exports.ping_server = ping_server;
module.exports.upload_files = upload_files;
With the idea that it will be used to recursively push files to a requested server if it can be pinged when the test device has internet connection.
I believe I have exported the methods correctly here using the module.exports syntax, I then try to include this module in my test.js file by using:
var uploader = require('uploader');
I also tried
var uploader = require('uploader.js');
But I believe node will automatically look for uploader.js if uploader is specified.
The file hierarchy for my app is as follows:
package.json
public
|-> lib
|-> test.js
|-> uploader.js
|-> css
|-> img
The only thing I am thinking, is that I heard node will try and source the node_modules folder which is to be included at the root directory of the application, could this be what is causing node not to find it? If not, why can node not see my file from test.js given they exist in the same directory?
UPDATE Sorry for the confusion, I have also tried using require('./uploader') and I am still getting the error: Uncaught Error: Cannot find module './uploader'.
UPDATE 2 I am normally completely against using images to convey code problems on SO, but I think this will significantly help the question:
It's clear here that test.js and uploader.js reside in the same location
When you don't pass a path (relative or absolute) to require(), it does a module lookup for the name passed in.
Change your require('uploader') to require('./uploader') or require(__dirname + '/uploader').
To load a local module (ie not one from node_modules) you need to prefix the path with ./. https://nodejs.org/api/modules.html#modules_modules
So in your case it would be var uploader = require('./uploader');
This problem stemmed from using Node Webkit instead of straight Node, as stated in their documentation all modules will be source from a node_modules directory at the root of the project.
Any internal non C++ libraries should be placed in the node_modules directory in order for Node webkit to find them.
Therefore to fix, I simply added a node_modules directory at the root of my project (outside of app and public) and placed the uploader.js file inside of there. Now when I call require('uploader') it works as expected.
If you're developing on a mac, check your file system case sensitivity. It could be that the required filename is capitalized wrong.
I am new with Nodejs. I want to export from file1.js file to file2.js.
file1.js is located in root-directory and file2.js is in some sub-directory. When I am calling it as require('/file1') in file2.js its saying like Uncaught Error: Module name "/file1" has not been loaded yet for context: _. Use require([]). Any help? Sorry if this is silly, but I am new.
var Logger = require('./logger');
Requires the module you have written, in a file called logger.js stored in the same directory your code was launched from.(not necessarily the same directory your code is stored in).
var someOtherModule = require('../../someOtherModule');
Requires someOtherModule.js file two directories back from where the node process is launched.
var someOtherModule = require('./subDir/someOtherModule');
Requires someOtherModule.js file, sotred in subDir. subDir is a directory located at the level of where the node process was launched.
var awssum = require('awssum');
Requires a module installed via NPM, in the node_modules directory from which the process was launched, or any globally installed node modules. For versioning, the node_modules directory takes precedence.
I have a executable node / javascript script that has a debug boolean, if set to true a couple of files will be written. This executable is also node module. Depending on the working directory of the user running the script it seems that the function can't find the directory to write files into.
The module is structured like this
output/
lib/
helpers.js
index.js
My original reasoning would be to have the path be.
helper.write = function(data,filename){
if(typeof data !== "string") data = JSON.stringify(data);
fs.writeFileSync("./output/"+filename, data);
};
However this works when running the script from within the node_module folder
fs.writeFileSync("process.cwd()+"/node_modules/the_module/output/"+filename, data);
Like this
node ./my_app/node_modules/the_module/index.js
This gets even more confusing if the modules is used in another executable file that uses the library.
node ./my_app/run.js
Is there a way to save the file independent from all of these variables?
If I understand the question correctly, you want to always write to a path relative to the current script. To get the name of the directory that the currently executing script resides in, you can use __dirname like so:
var path = require('path');
helper.write = function(data,filename){
if(typeof data !== "string") data = JSON.stringify(data);
var file = path.join(__dirname, 'output', filename);
fs.writeFileSync(file, data);
};
That being said, I don't think it's good practice to be writing files inside of your node_modules directory. I'd recommend that your module require the full path to a file somewhere else in the file system. If the caller wishes to write to an output directory in its own project tree, you can again use the same __dirname trick.