Cannot find module './models/user' | Node.js - node.js

I am making auth in node.js and I have a dir called models, and a file in there to make the user, called user.js.
In the app.js file is the statement var User = require('./models/user');, and yet it can't find that file.

Did you add module.exports = ... // function or object or other variable in the user.js file at the bottom?

Related

Exported object is empty

I'm struggling since 2 days on something that shouldn't block me.
Basically, I'm building a nodeJS app that uses Express.
In my main file (located in my root folder), i'm exporting some variables/consts, for the purpose of the example I replaced them like this :
// ./index.js
const test = 'test'
module.exports = { test }
... some express initialization/routers
I then have another file that I want to use the "test" variable in, so I require my main file :
// ./aaa/bbb/ccc/test.js
const { test } = require('../../../index);
const myRouter = require('express').Router();
myRouter.get('/', function (req, res){
console.log(test) // undefined
})
I don't really know why it would be undefined as I correctly exported it, and "imported" it through my require statement.
I also tried "consoling" the whole object that I should receive, and it's empty : {}
EDIT : my "main" script that i'm executing is indeed index.js, but I highly doubt it's the reason of the problem
I can't really find out what could be the problem, and I need to export some variable to access them in my project
Thanks!
I think you did it right. The problem may be that es6 features are not acceptable on your node version. Try it like: module.exports = { test:test }.

return value to app.js file in node js

I have two files, one called filename and the second called app.js, both files are on the server side. From filename.js filder I am returing a value string from ensureAuthentication method to app.js file, so i export the function:
function ensureAuthentication(){
return 'tesstestest';
}
exports.ensureAuthentication = ensureAuthentication;
in app.js file i do following
var appjs = require('filename');
console.log(appjs.ensureAuthentication);
result is always is undifined in console??! why is that any idea?
You should try this in your app.js -
var login = require('filename');
console.log(login());
or you can use this :
var login = require('filename')();
console.log(login);
Explanation: Whenever you are exporting a function using exports you need to execute it to get the return value from it.
Try this:
var appjs = require('filename');
console.log(appjs.ensureAuthentication());
note the () after the function call. This will execute your function. The console.log() call will then print the returned value.
Try this, make sure both files are in the same directory. You have a few errors with your code. Missing brackets, and not importing correctly in app.js.
filename.js
function ensureAuthentication(){ // You are missing the brackets here.
return 'tesstestest';
}
exports.ensureAuthentication = ensureAuthentication;
app.js
var appjs = require('./filename'); // You are missing the ./ here.
console.log(appjs.ensureAuthentication()); // Logs 'tesstestest'
Two problems with your code:
You need to require with a relative path (notice the ./):
var appjs = require('./filename');
To get the string value you need to invoke ensureAuthentication as a function:
console.log(appjs.ensureAuthentication());
UPDATE
This update addresses the screenshot posted in the comments.
In the screenshot you pasted in the comments, you have the following line:
module.exports = router
That assigns a different exports object to the module. So your local reference to exports is no longer the same object.
Change that line to
module.exports = exports = router
Which will preserve the reference to exports which you use next.
Here you go with the working code
filename.js
function ensureAuthentication(){
return 'tesstestest';
}
module.exports = {
ensureAuthentication : ensureAuthentication
}
app.js
var appjs = require('./utils/sample');
console.log(appjs.ensureAuthentication());

reuse moongoose connection in other files

I realize mongoose is a singleton and once you do mongoose.connect in one file and later all scripts that require this file will have mongoose connected as well.
But shouldn't that mean when I execute another test script that only has require('mongoose') in it and it will show that I am connected to mongodb too because the previous script (which starts an http server) is still running and I am referencing the the same mongoose inside node_modules? Thanks.
UPDATED
Here is an example of a file: myLib.js inside my /lib directory
exports.someVar = [5,4,3,2,1];
exports.printSize = function(){
console.log(exports.someVar.length);
}
Now let's create an other file named app.js and include the myLib.js:
var myLib = require("./lib/myLib.js");
var http = require("./http.js");
console.log("app.js:");
myLib.printSize(); // will print 5
myLib.someVar.push(100);
console.log("app.js:");
myLib.printSize(); // will print 6
console.log("calling http");
http.start();
console.log("app.js:");
myLib.printSize(); // will print 7
Okay, now let's create an other file, named http.js and include the myLib.js too:
var myLib = require("./lib/myLib.js");
exports.start = function(){
console.log("http.js:");
myLib.printSize(); // will print 6
myLib.someVar.push(200);
}
Now lets create a project for myLib.js and replace all lines:
var myLib = require("./lib/myLib.js");
to:
var myLib = require("myLib");
And the result will be the same, that is the why the mongoose connection are active even when you use require("mongoose") in other parts of your project.
After you create a connection, the variable will be available for other parts of your project.
It is like a singleton, so you do not need create your own for hold the connection reference.

Express.js db module after refactoring routes

I had a simple app in node/express and after watching a course on the net, it helped me refactor the routes in my app but I found a little problem after doing so.
The problem is that my routes are using a variable called "db" that is an instance of a nedb access point.
var db = {
users: new nedb({ filename: "db/users.db", autoload: true })
};
Of course I can copy the 5 lines of code in the top of every route file to declare it but that would not be very DRY.
I tryed to put it in a separate file and export the variable:
...
module.exports = db;
And then import it in every file with:
var db = require("./db");
...
But this didn't worked as expected (The error was : Cannot find module './db')
This is a simplified structure of my files
db/
users.db
routes/
users.js
app.js
db.js
Any ideas or best practice/elegant way for solving this?
Thank you.
you need to require with a relative path. If you require inside /routes folder, you must write
var db = require("../db");

Dealing with Relative Paths with node.js

I'm wanting to include a .db database file for use with sqlite3 in my node.js project. My problem arises when the module which opens the database connection is required by files in different directories.
My project structure is like so:
project/
|--lib/
| |--foo.js
| `--bar.js
|--db/
| `--database.db
`--server.js
My foo.js file contains opens the database like so:
var sqlite3 = require('sqlite3');
var db = new sqlite3.Database('db/database.db');
module.exports = {
foo: function() {
db.serialize(function() { /* Do database things */ });
}
};
This all works fine when foo.js is required from the server.js file like so:
var foo = require('./lib/foo');
But it doesn't work when required from the file inside the lib directory, bar.js.
var foo = require('./foo');
I assume this is because when this file is initiated from the lib directory then the .db file should actually be ../db/database.db.
How can I get around this, what should I do?
the concept current directory differs when using sqlite3.Database function in different scripts. it works as designed in this line of sqlite3 source code.
So you should explicitly specify the current directory every time you use it. According to your project layout, the correct path to database file in lib/foo.js is
var path = require('path')
// specify current directory explicitly
var db = new sqlite3.Database(path.join(__dirname, '..', 'db', 'database.db'));
Then it works no matter where it requires foo.js.

Resources