Node.js - "Cannot find module", when the module call other module - node.js

I'm developing my first Node.js App. and Everything is find, but Now the app is getting bigger. and I'd like to divide the app into different files. So, I used a "require" method to divide a app into files.
but My App display "Cannot find module".
** Call Ordering **
A.js is call B.js <-- call is ok
B.js is call C.js <-- Cannot Find module, B.js can't call 'test222 function'
My Sample Code.
a.js
...
var m=require('./controller/b.js');
m.register(req,res);
b.js
exports.register=function(){
var MyModule=require('./model/c.js');
console.log(MyModule.test222()); <--------- cannot find module
};
c.js
exports.test222=function() {
return "c.js";
};
Help me or advice. thank you.
I want to Call module in another module. but My Node App is not working for "cannot find module". How to solve it?

It seems that you've mistyped by writing var m=require('./controller/a.js'); instead of var m=require('./controller/b.js');
If so, I can see that you have the following file structure:
./a.js
./controller/b.js
./model/c.js
So you run ./a.js which requires ./controller/b.js and it works fine. But when ./controller/b.js requires ./model/c.js, Node resolves c.js as ./controller/model.js, because each module is relative to the file calling require().
This is why error occurs.
To solve this problem you should replace
var MyModule=require('./model/c.js');
with
var MyModule=require('../model/c.js');

the require function automatically search for modules at the node_modules folder
by just typing the name of the module with the js. extension
var b=require('b.js');
var c=require('c.js');
but if you make changes to the structure of your node_modules folder you need to navigate to your moduleusing the relative waie by taping
"../"
to navigate from a child directory to the parent directory and
"./"
to navigate from the parent directory to the child directory
You need to respect the relative way.

Related

Node / express - require exported js file inside route file

I created an app using express generator. I have a js file in my public/javascripts directory. I exported an obj:
module.exports = { my obj here }
Then in my route file (index.js) I've been trying to serve this object as an API so I can fetch it from another js file and do stuff on the front end.
But my require simply won't work. I tried:
var specs = require('./javascripts/specs')
and all variation of the path cause I assumed that my path was wrong.
Am I missing something obvious? I get the following error:
Error: Cannot find module '/javascripts/specs'......
File Structure
https://www.dropbox.com/s/ou9afzckboxbe1w/Screenshot%202018-04-18%2011.59.32.png?dl=0
Your public folder and your routes folder are on the same level in your directory. Therefore you need to go up to the common parent, then down through public/javascripts like this:
var specs = require('../public/javascripts/specs');
Your public/javascript is for client only scripts, if you want to require it from the server you have to provide the full path :
var specs = require('../public/javascripts/specs');

Why can node not find my module?

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.

what gets called first when a directory is treated as a function?

The open source blogging project Ghost has an index.js file with just this code in it.
// # Ghost bootloader
// Orchestrates the loading of Ghost
// When run from command line.
var ghost = require('./core');
ghost();
If you run node index.js, it starts the application. The ./core in the require statement is actually a directory with a lot of sub-directories in it, so this index.js file is essentially calling the whole directory (which has many functions and files in it) as a function ghost();, which begs the question, what is actually being called first when ghost(); happens? Will it automatically look for an index.js file inside the /core directory?
For example, inside ./core, in addition to a bunch of other directories, there's also this index.js file with one function in it startGhost
// # Ghost bootloader
// Orchestrates the loading of Ghost
// When run from command line.
var config = require('./server/config'),
errors = require('./server/errorHandling');
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
function startGhost(app) {
config.load().then(function () {
var ghost = require('./server');
ghost(app);
}).otherwise(errors.logAndThrowError);
}
module.exports = startGhost;
so my question is, when there's a setup like this where a whole directory is called like a function
var ghost = require('./core');
ghost();
is node's default to look for an index.js file inside ./core, and, in this case, call startGhost?
The way I understand it is that
var ghost = require('./core');
ghost();
and
var ghost = require('./core/index.js');
ghost();
are equivalent. In other words, requiring a directory is just short hand for requiring the index.js in that directory.
To deal with the second part of your question, your index.js exports a function. This means that when you require index.js your variable will contain a function with you can then call, in your case with ghost().
It is important to understand that modules don't have to export a function, they can export an object and other things as well. This post explains it well.

How to get the path of this file in nodejs?

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.

PhantomJS require() a relative path

In a PhantomJS script I would like to load a custom module but it seems relative paths do not works in PhantomJS ?
script.js:
var foo = require('./script/lib/foo.js');
foo.bar('hello world');
phantom.exit();
foo.js:
exports.bar = function(text){
console.log(text);
}
According to fs.workingDirectory I am in the good directory
foo.js is not in the lookup path of phantomjs
Am I missing something ?
EDIT:
inject() is not revelant because I do not need to inject a JS to an HTML page but instead load my own module like require('fs') but with a relative path.
After a lot of time searching for the same thing, here is what I understood, though I might be wrong :
PhantomJS doesn't use Node's require, but its own require, so things are different
when providing a relative path to phantomjs's require, it is always interpreted as relative to the current working directory
PhantomJS doesn't implement node's __dirname, and as such there is no direct way to have the directory of your script
The solution I found least annoying :
if using phantomjs pure, without casperjs :
require(phantom.libraryPath + '/script/lib/foo.js')
if using casperjs :
var scriptName = fs.absolute( require("system").args[3] );
var scriptDirectory = scriptName.substring(0, scriptName.lastIndexOf('/'));
require(scriptDirectory + '/script/lib/foo.js')
To load your own module, the right way to do it is to use module.exports, like this: foo.js
function bar(text) {
console.log(text);
}
exports.bar = bar
And in script.js (which is executed with phantomjs script.js):
var foo = require('./script/lib/foo');
foo.bar('hello world');
phantom.exit();
My solution to load a resource file (like let's say a json file) within a phantomjs subfolder from a outer folder like in this structure:
├── consumer.js
├── assets
├── data.json
├── loader.js
Supposed that data.json must be load by the consumer module and that this module is called by somewhere else on this machine, outside the project root folder, the fs.workingDirectory will not work, since it will be the path of the caller file.
So to solve this, I did a simple loader module within the assets folder, where the files I want to load are:
(function() {
var loader = {
load : function(fileName) {
var res=require('./'+fileName);
return res;
}
}
module.exports=loader;
}).call(this);
I therefore call the loader module from the consumer module like
var loader=require('./data/loader');
var assets=loader.load('data.json');
and that's it.
NOTE. The require here is the phantomjs require not the node version, so it works a bit differently. In this case the data.json was a json array with no module.exports declaration. The array will be backed in the assets variable directly when calling the loader.load(fileName) method.
have you tried to use injectJs(filename)
excerpt form PhantomJS documentation:
Injects external script code from the specified file. If the file can
not be found in the current directory, libraryPath is used for
additional look up.
This function returns true if injection is successful, otherwise it
returns false.
Which PhantomJS version are you running? Support for user provided modules was added in 1.7.

Resources