that is my db.js from where i am exporting the function
var mysql=require('mysql');
var config=
{
host:'127.0.0.1',
user:'root',
password:'',
database:'travel'
};
var con="";
var data=function getConnection()
{
con=mysql.createConnection(config);
con.connect(function(err)
{
if(err!=null)
{
console.log('connection id: '+con.threadId);
}
else
{
console.log('connection error: '+err.stack);
}
})
};
module.exports=data;
and here is my login.js file from where i am calling that exported data function
var express=require('express');
var db = require.main.require('./model/db');
var router=express.Router();
//routes
router.post('/',function(req,res)
{
console.log(req.body);
});
router.get('/',function(req,res)
{
data();
res.render('login');
});
module.exports = router;
Here is the error message after running the code. can anyone please help me with that problem?
You should change the import statement as follows, because you are invoking the data() not db(). so you should change the import statement to data instead of db
var data = require.main.require('./model/db');
When you use module.exports you're specifying the object that is exported, not a name or set of names. Since you literally just export the data function you want to use, the line var db = require.main.require('./model/db'); first creates/finds that function and then assigns it to the variable db -- the original name doesn't matter at all.
Possible solutions to that problem (as indicated in the other answers) include replacing data() with db() or replacing var db with var data.
Related
How do I call the function expression "extractUserProgress" which is situated in an external module from server.js?
EDIT
I have clarified further what is happening in my code.
I have a chain of function expressions in my module that follow from "extractUserProgress". The last function returns an array which is what I'm after.
//setGen.js (module file)
module.exports = function(app, db) {
var extractUserProgress = function() {
//Access mongoDB and do stuff
nextFunction(x)
}
var nextFunction = function(x) {
let y = [];
//calculate y
return y // this is what i'm after
}
}
//server.js
const setGen = require("./setGen")
app.get("/setGen", function(req, res){
//data here from select input
extractUserProgress //How to call from here?
console.log(y) //array from module
});
I have required the module in server.js but not sure how to export function in this scenario where the functions in module also needs to access mongoDB.
Thanks
You can achieve this easily if you change the structure of your exports a little.
const extractUserProgress = function (app, db) {
console.log('This can be called');
//Access mongoDB and do stuff
}
module.exports = {
extractUserProgress
};
you can call this function from the otherside this way.
const newFile = require('./server');
newFile.extractUserProgress(); // you can pass arguments APP and DB to this function
With the code as-is, you can't - extractUserProgress is not accessible, it's declared inside the exported function scope.
If you need it accessible, and also need to keep the exported signature, then you can return a hash of functions e.g.
module.exports = function(app, db) {
...
return {
extractUserProgress(...) {
...
},
// More functions
}
}
// Usage
const setGen = require('./setGen')(app, db)
setGen.extractUserProgress(...);
If you don't need to maintain the existing exported function, then you can export the functions as a hash instead
module.exports = {
extractUserProgress(...) {
...
},
// More functions
}
// Usage
const setGen = require('./setGen')
setGen.extractUserProgress(...);
In node.js I have this scenario:
main.js
module.exports = {
dbHandler: {}
}
const DB_CONNECT = require('dbConnect.js');
const CHILD_MODULE = require('childModule.js');
module.exports.dbHandler = DB_CONNECT.connectDB(); // establishes the connection to the sqlite3 db
// ... give some time to module.exports.dbHandler to be loaded. (lab testing)
CHILD_MODULE.queryDB(); // <----- error occurs
childModule.js
var db = module.parent.exports.dbHandler;
//issue is here. Even after the parent have set dbHandler, this still empty {}.
module.exports.queryDB = function(){
db.all('SELECT * from mytable', (err, rows) => { // callback
console.log(rows);
}
Since DB_CONNECT.connectDB() is async, I give it a while (lab test) to load the database and updating module.exports.dbHandler before calling CHILD_MODULE.queryDB()
the error occurs when db.all is called.
TypeError: db.all is not a function
db still an empty object {}.
What is wrong in this code? How do I make the child's db to access the parent's module.exports.dbHandler ?
First of all, I will not fix your problem directly. I will try to explain my comment in above.
I have had a similar scenario in one of my projects. But I have used MongoDB. My db model looks like this:
var MongoClient = require('mongodb').MongoClient
var url = process.env.MONGO_URI
var collection = 'shortlinks'
var state = {
db: null
}
exports.connect = function (done) {
if (state.db) return done()
MongoClient.connect(url, function (err, db) {
if (err) return done(err)
state.db = db
done()
})
}
exports.get = function () {
return state.db
}
...
and some other methods
And I have accessed this module from different places for the same database connection with this line:
var db = require('../models/db')
I can access the same db instance with getter method and other methods as well.
I am creating an API with Node.js and Express. I'm using Postgres as DB.
I would like to create a "global object", called DBConn or something, that I can access from everywhere in the App. This object would have the functions for inserting, updating, validating, etc.
How would be the general architecture in Node and Express for this to work? Does it make sense in Node to instantiate it just once and keep the communication with the DB open, or should I instantiate it everytime I want to perform a DB action?
Here's everything that you are looking for, using pg-promise:
// Users repository:
var repUsers = function (obj) {
return {
add: function (name) {
return obj.none("insert into users(name) values($1)", name);
},
delete: function (id) {
return obj.none("delete from users where id=$1", id);
}
// etc...
};
};
var options = {
extend: function () {
// extending the protocol:
this.users = repUsers(this);
}
};
var pgp = require('pg-promise')(options);
var cn = "postgres://username:password#host:port/database";
var db = pgp(cn); // your global database instance;
db.users.add("John")
.then(function () {
// success;
})
.catch(function (error) {
// error;
});
This will also manage your database connection automatically, you will just keep using variable db throughout your application.
And setting up a repository is optional, you can always use in-line queries instead. See the library for details and more examples.
I don't know Postgres at all,but maybe you can try this:
Create a file named 'DBConn.js' in YourApp/common directory.
DBConn.js:
var DBConn = exports = modules.exports = {}
//code to connect to database
....
//insert update detele select
DBConn.insert = function(arguments) {
//some code
}
.....
DBConn.update = function(arguments) {
//some code
}
Then you can require it in any other controller like YouApp/controller/UserController.js
UserController.js:
var DBConn = require('../common/DBConn.js')
Example of module cache
index.js:
require('./DB.js');
require('./DB.js');
DB.js
var DB = exports = module.exports = {}
function connect() {
//connect to database code
console.log('Connect!');
}
connect();
//other code
Then node index.js,we can see that 'Connect!' only logged once.
Because when we first require('DB.js'),node.js put it to the module cache,and when we require DB.js again,we get DB.js from cache.
This question already has answers here:
What is the purpose of Node.js module.exports and how do you use it?
(13 answers)
Closed 7 years ago.
Say I have the following module makeDir which checks for the existence of a directory and creates one if it does not exist or simply calls its callback with null if the directory already exists.
Which would be the proper way to export this module?
module.exports = makeDir or module.exports.makeDir = makeDir ?
'use strict';
var fs = require('fs');
var mkdirp = require('mkdirp');
var makeDir = {};
makeDir.handler = function (dstPath, sizesObj, callback) {
var _path = dstPath + sizesObj.name + "/";
fs.lstat(_path, function (err, stats) {
if (err) {
mkdirp(_path, function (err, made) {
if (err) {
console.log("Error creating directory: %s", err);
callback (err, null);
} else {
console.log("Created new directory");
callback(null, made);
}
});
} else {
callback(null);
}
});
};
module.exports = makeDir;
Both methods of using module.exports or module.exports.FUNCTION_NAME are okay but the difference comes when you require these functions.
Let me show the difference using an Example.
a. Assigning function directly to module.exports
// mkdir.js
module.exports = function(){
console.log("make directory function");
};
// app.js
var mkdir = require("mkdir.js");
mkdir(); // prints make directory function
b. Exporting function at property in module.exports
// mkdir.js
module.exports.first = function(){
console.log('make directory function');
};
// app.js
var mkdir = require('mkdir.js');
mkdir.mkdir(); // make directory function
Hope it helps!
module.exports = makeDir;
is the correct method if you are exporting only one object from javascript file.
IN CASE YOU NEED TO EXPORT MORE THAN ONE OBJECTS
var makeDir = {
obj1 : function(){},
obj2 : function(){}
}
module.exports = makeDir;
This way you can use makeDir.obj1 and makeDir.obj2 in other file.
how do i share the db object returned from when i call db.open or db.connect across the entire app?
i have a dbconnect.js module as follows :
var mongodb = require('mongodb');
var global_db = '';
// Define options. Note poolSize.
var serverOptions = {
'auto_reconnect': true,
'poolSize': 5
};
// Now create the server, passing our options.
var serv = new mongodb.Server('localhost', 27017, serverOptions);
// At this point, there is no connection made to the server.
// Create a handle to the Mongo database called 'myDB'.
var dbManager = new mongodb.Db('myDB', serv);
// NOW we initialize ALL 5 connections:
dbManager.open(function (error, db) {
// Do something with the connection.
global_db = db;
// Make sure to call db.close() when ALL connections need
// to be shut down.
db.close();
});
function getConnection()
{
return global_db;
}
exports.getConnection = getConnection;
and i am using this dbconnect.js in my app.js as:
var http = require('http');
var db = require('./dbconnect').getConnection();
var collection = db.collection('testcollection');
console.log(db);
console.log(collection);
var server = http.createServer();
server.on('request',route);
server.listen(8000,'127.0.0.1');
console.log('Server running at http://127.0.0.1:8000');
function route(request,response)
{
var url = request.url;
var doc = {};
doc[url] = 'ok';
collection.insert(doc,{w:1},function(err,result)
{
if(err) console.log(err);
else console.log(result);
});
}
in the console, the db and collection variable show empty values, i also tried removing the db.close() call in dbconnect.js but to no use, however the insertion works when i place it inside dbconnect.js file in the dbManager.open function, how do i do this?or any similar alternatives?
You can't do that, because dbManager.open( is async method, but you trying to get data from module synchronously.
Try this:
In dbconnect.js
var on_db_ready = null;
module.exports = {
db_ready:function(db_ready_callback){
on_db_ready = db_ready_callback;
//here we call callback if already have db
if (global_db) on_db_ready(global_db);
},
getConnection:getConnection
};
dbManager.open(function (error, db) {
if (on_db_ready) on_db_ready(db);
global_db= db;
})
in app.js:
var db = require('./dbconnect').db_ready(function(db){
//Here i have my database
//or can use getConnection method
});
this is not very beautiful way, but, I hope, explain your mistake