does not work module.exports - javascript

file ConnectToDB
var pg = require("pg");
var dataWithDB = require('./DataBase/ConnectToDb');
var pool = new pg.Pool({
host: "localhost",
port: "5432",
user: "postgres",
password: "111111",
database: "hrs"
});
pool.connect(function (err,client,done) {
if(err)console.log("connect " + err.toString());
else
client.query('SELECT id, "idName", "idContact", "idExperience",
"idSkill", "dateAdded", "dateColloquy"' +
'FROM public."applicant ";',function (err,result) {
if(err) {
//console.log("query " + err.toString());
exports.res = "Data NOT";
}
else {
console.log(result.rows);
module.exports.resul = result.rows;
}
done();
});
});
pool.end()
file app.js
var dataWithDB = require('./DataBase/ConnectToDb');
console.log(dataWithDB + " wit DB");
as a result deduces to me undefined wit DB
but should data from db
Can an error in the scope?
Data is sent if you specify at the end of the file module.exporst.result = "Example".

You should encapsulate your connect to db code in a function which takes a callback.
Here is an example, hopefully you get the idea. :)
./DataBase/ConnectToDb
var pg = require("pg");
module.exports = (callback) => {
var pool = new pg.Pool({
host: "localhost",
port: "5432",
user: "postgres",
password: "111111",
database: "hrs"
});
pool.connect(function (err, client, done) {
if (err) {
console.log("connect " + err.toString());
} else {
let query = 'SELECT id, "idName", "idContact",' +
' "idExperience","idSkill", "dateAdded", "dateColloquy"' +
'FROM public."applicant ";'
client.query(query, function (err, result) {
if (err) {
//console.log("query " + err.toString());
exports.res = "Data NOT";
callback(err);
}
else {
console.log(result.rows);
callback(null, result);
}
done(); // Not sure what this does! :-o
});
}
});
// Is this trying to close it before we've connected?
// It should probably be up above...
pool.end()
}
app
var connectToDb = require('./DataBase/ConnectToDb');
connectToDb((err, result) => {
// This is a callback!
if(err) console.log(err)
else console.log(result)
})
Do a google search for: node.js callback pattern

Here is what you should do: import a different callback function that you pass into your query. This callback will do whatever you want with result. As written, your method will not work and does not make sense.

Related

How to correctly write module in Node.JS?

So I'm trying to make it so I don't have to have multiple connections to my database when I can just put my connection and runQuery function in a file and just require it in another file. Here is what I have in my "mysql.js" file.
const mysql = require('mysql');
module.exports = function () {
let connection = mysql.createConnection({
host: '------',
user: 'voltclou_site',
password: '----',
database: process.env.database
})
connection.connect(function(err) {
if (err) {
console.error('[DATABASE] Error connecting: ' + err.stack);
return;
}
console.log('[DATABASE] Connected as id ' + connection.threadId);
});
async function runQuery(query, values) {
return new Promise((resolve, reject) => {
connection.query(query, values, function (error, results) {
if (error) return reject(error)
return resolve(results)
})
})
}
}
Here is how I would like to require it in my files:
const { connection, runQuery } = require('./functions/mysql')
Am I doing this correctly? I'm new to this whole module thing. I've been trying to split my files up because one index.js with 3000+ lines is insane. Thanks for any help.
No you didnt do it correclty. What you have done you have exported it as an default but you want to export named functions. You can do it like:
const mysql = require("mysql");
let connection = mysql.createConnection({
host: "81.19.215.6",
user: "voltclou_site",
password: "yogO{6,F#8WS",
database: process.env.database
});
connection.connect(function(err) {
if (err) {
console.error("[DATABASE] Error connecting: " + err.stack);
return;
}
console.log("[DATABASE] Connected as id " + connection.threadId);
});
async function runQuery(query, values) {
return new Promise((resolve, reject) => {
connection.query(query, values, function(error, results) {
if (error) return reject(error);
return resolve(results);
});
});
}
module.exports = {
connection,
runQuery
};
The value you've described, { connection, runQuery }, should be the value assigned to module.exports:
const mysql = require('mysql');
let connection = mysql.createConnection({ ... });
connection.connect(...);
let runQuery = async (query, values) => { ... };
module.exports = { connection, runQuery };
You may not even need to export connection, if all you need elsewhere is runQuery!

Node MYSQL exports returns undefined

I am creating a discord bot that has integration with mysql. To make it easier, I created a central file for the mysql database (configs/mysql.js) and, when the command needs it, it will send the query request to that file and finally, it will return the processed value. But when I try to do this, the return is undefined in the console (of the command), but in the mysql.js console, it shows the correct value.
MYSQL.js Code
const mysql = require("mysql");
const connection = mysql.createConnection({
host: config.URL,
user: config.dbUser,
password: config.dbPassword,
database: config.database
});
connection.connect(function(err) {
if (err) {
console.error("[MYSQL] Error on Connection: " + err.stack);
return;
}
console.log("[MYSQL] Connected with ID " + connection.threadId + "!");
});
function query(sql) {
connection.query(sql, function(error, result, fields) {
if (error) return error;
const analise = JSON.stringify(result[0]);
console.log(analise) //it's return the value correct
return analise
});
}
exports.connection = connection;
exports.query = query;
The Request
const status1 = await mysql.query("SELECT `status` FROM `server_status`");
console.log(status1); //it's return undefined
Can anyone help me?
Use promise for mysql you can`t use return in callback function.
const mysql = require('mysql');
const connection = mysql.createConnection({
host: config.URL,
user: config.dbUser,
password: config.dbPassword,
database: config.database,
});
connection.connect(function(err) {
if (err) {
console.error('[MYSQL] Error on Connection: ' + err.stack);
return;
}
console.log('[MYSQL] Connected with ID ' + connection.threadId + '!');
});
function query(sql) {
return new Promise(resolve => {
connection.query(sql, function(error, result, fields) {
if (error) return error;
const analise = JSON.stringify(result[0]);
console.log(analise); //it's return the value correct
resolve(analise);
});
});
}
exports.connection = connection;
exports.query = query;
const status1 = await mysql.query("SELECT `status` FROM `server_status`");

Node.js module export "pre-load"

This is in a mysql.js file:
const mysql = require('mysql');
const config = require('./config.json');
const con = mysql.createConnection({
host: config.dbhost,
user: config.dbuser,
password: config.dbpass,
database: config.dbname,
});
module.exports = {
findUser: function(email) {
const sql = 'SELECT * FROM users WHERE email = ' + mysql.escape(email);
con.connect(function(err) {
if (err) throw err;
console.log('Connected!');
con.query(sql, function(err, result) {
if (err) throw err;
return result[0].id;
});
});
},
};
then within my index.js file there is this:
const mysql = require('./mysql.js');
console.log(mysql.findUser('example#example.test'));
When the code is running, it outputs "undefined" and then "Connected!" after the db connection is made. Even though if I do a console.log on result[0].id it outputs 1, which is the correct id...
Question: How can I load the mysql.js file first before the function is called?
You need to wait for response cause its an asynchronous function.
Try using callback or promises.
Callback example:
mysql.findUser('example#example.test', function(res)){ console.log(res)});
module.exports = {
findUser: function(email, callback) {
const sql = 'SELECT * FROM users WHERE email = ' + mysql.escape(email);
con.connect(function(err) {
if (err) throw err;
console.log('Connected!');
con.query(sql, function(err, result) {
if (err) throw err;
callback(result[0].id);
});
});
},

How to get result from function in other file in node.js

Trying to call database query from other javascript file in NodeJS.
Sample database file:
function addUser(user) {
connection.connect(function (err) {
if (err) {
console.error('Error connecting: ' + err);
}
console.log('Connected as id ' + connection.threadId);
});
var sql = "INSERT INTO `mobile`.`main` (`userId`) VALUES (?);"
var inserts = [user];
connection.query(sql, inserts, function (error, results) {
console.log('query');
if (error) {
return error;
} else {
console.log('Success Query');
return results;
}
});
connection.end(function (err) {
if (err) {
console.error('Error connecting: ' + err);
}
console.log('Connection closed!');
});
}
module.exports = addUser;
Sample main.js file:
app.get('/api/mysql/:user', function (req, res) {
var user = req.params.user;
addUsers(user)
res.json({
SQLResp: 'Query succes',
result: addUsers.result
});
});
How to get the result from the first file and use it as a response in the main js?
Welcome to stack overflow.
this is missing from your database file, How did you got connection there?
Here's a sample example over How to export database connection and use this to make calls from other files.
Also do read about callbacks-functions, Promises, async-await and Asynchronous functions of JavaScript. These are basics of JavaScript and also do go through NodeJS docs.
DB.js:
const MYSQL = require('mysql');
const connection = MYSQL.createConnection({
host: 'localhost', // url of db
user: 'root',
password: 'root',
database: 'dbName'
});
module.exports = connection;
Now will use this connection from other file to call database.
app.js:
const db = require('./DB'); // Path of your db connection file. I named it DB.js on same level as of app.js
function addUser(user) {
// Since database calls are async in NodeJS thus using promises.
return new Promise ( (resolve, reject) => {
db.connect(function (err) {
if (err) {
console.error('Error connecting: ' + err);
return reject(err);
}
console.log('Connected as id ' + connection.threadId);
});
var sql = "INSERT INTO `mobile`.`main` (`userId`) VALUES (?);"
var inserts = [user];
db.query(sql, inserts, function (error, results) {
console.log('query');
if (error) {
return reject(err);
} else {
console.log('Success Query');
return resolve(results);
}
});
db.end(function (err) {
if (err) {
console.error('Error connecting: ' + err);
}
console.log('Connection closed!');
});
});
}
app.get('/api/mysql/:user', function (req, res) {
var user = req.params.user;
addUsers(user)
.then (result => { // When addUsers will resolve promise will be in then.
res.json({
SQLResp: 'Query succes',
result: result
});
})
.catch(err => { // If promise is rejected then on catch
res.json({
SQLResp: 'Query err',
result: err
});
});
});
You need to pass a callback into your addUser function, and call it inside your connection.query with the results.
Currently, when you return, you're returning inside another callback, which means the data is more or less being thrown away.
That will also let you handle all of the error cases in a way you can tell the user about.

Last callback not being called using async

I cannot seem to get the last callback (commented as "optional callback") called to send the result back to the browser. Any pointers as to what I am doing wrong? I am using the following modules: async, restify and postgresql for node.js
console.log('Start');
var async = require('async');
var restify = require('restify');
var server = restify.createServer();
server.use(restify.bodyParser());
server.get('/user/creationdate/:username', function(req, res, next) {
var userName = req.params.username;
var record;
async.parallel([
function(callback){
getUserByName(userName, function(err, user) {
if (err) return callback(err);
record = user;
});
}
],
// optional callback
function(err){
console.log('5. Following record has been retrieved:' + record);
res.send(record);
});
next();
});
server.listen(8080, function () {
console.log('%s listening at %s', server.name, server.url);
});
handleError = function handleError(err) {
if(!err) { return false; }
else {
console.log('The following error occurred:' + err);
}
return true;
};
function getPgClient(){
var pg = require('pg');
var client = new pg.Client({
user: 'postgres',
password: 'password',
database: 'foobar',
host: '192.168.1.100',
port: 5432
});
client.on('drain', client.end.bind(client)); //disconnect client when all queries are finished
return client;
}
function getUserByName(userName, callback){
var client = getPgClient();
console.log('2. Trying to connect to DB');
client.connect(function(err) {
console.log('3. Error connecting to DB:' + handleError(err));
if(handleError(err)) return callback(err);
client.query("SELECT created_at FROM users WHERE username='" + userName + "'", function(err, result) {
if(handleError(err)) return;
console.log('4. Error occurred:' + err);
console.log(result);
console.log(callback);
callback(null, result);
})
});
}
I'm not sure why you're using async since you're only calling one asynchronous function. But the reason your callback isn't called is because you're not ending the first function by calling its callback:
async.parallel([
function(callback) {
getUserByName(userName, function(err, user) {
// call async callback with err and user
callback(err, user);
});
}
], function(err, record) {
console.log('5. Following record has been retrieved:' + record);
res.send(record);
});
Or, shorter:
async.parallel([
function(callback) {
getUserByName(callback);
}
], function(err, record) {
console.log('5. Following record has been retrieved:' + record);
res.send(record);
});
Or, in this case, even shorter (and without the need for async):
getUserByName(function(err, record) {
// handle error, or ...
console.log('5. Following record has been retrieved:' + record);
res.send(record);
});
Saw my mistake, missing the line where I should have returned the callback as in:
async.parallel([
function(callback){
getUserByName(userName, function(err, user) {
if (err) return callback(err);
record = user;
return callback(null, record);
});
}

Categories

Resources