Export mysql2 connection to other files node js - javascript

I am trying to use one connection across all the files in a node and mysql2 project.
This is what I did ->
// db.js
const mysql = require('mysql2')
const connection = mysql.createConnection({dbinfo})
console.log(connection) // the connection is proper
module.exports = { connection }
//server.js
const { con } = require('./db')
console.log(con) //returns undefined
Similar thing works if I use the mysql package instead with mysql2

Related

How to reuse Redis connection using nodeJs childProcess

How could I reuse the redis connection in processes created using Childprocess.fork() in nodeJs ?
For example, I would have a redis-config.js file where I create an instance of RedisClient and connect to the redis server.
So after that I would have another file, test.js for example, and inside that file test, js I would access the instance of redis via import and then I could for example insert a key in redis. But this without creating another connection to the redis server.
For example
redis-conf.js
const Redis = require('redis');
const redisClient = Redis.createClient({name:'test-conecction'});
module.exports = {redisClient:Object.freeze(redisClient)}
main.js
const cp = require('node:child_process');
const {redisClient} = require('./redis');
redisClient.connect().then(()=>{ <<=== this is want i want, this does not work, i want to connect only once.
const c1 = cp.fork('./child.js');
const c2 = cp.fork('./child.js');
})
child.js
const {redisClient} = require('./redis');
redisClient.info().then((data)=>{ <<== when i try this, nodeJs tells that the client is disconnected
console.log(data);
})
IN resume. Its not possible. Because when nodeJs create a childPorcess evething is re-created and all resources are re-alocated.

Node.js require connection inside multiple module

I have a question about the require function of Node.js, imagine we have a module that manages the connection, and many small modules that contain the routes.
An example of connection file: db.js
const mysql = require('mysql');
const connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : '',
database : 'chat'
});
connection.connect(function(err) {
if (err) throw err;
});
module.exports = connection;
and one of the various files to manage the routes:
const app = express();
const router = express.Router();
const db = require('./db');
router.get('/save',function(req,res){
// some code for db
});
module.exports = router;
Imagine now to have 20 routes with the same require. How will node.js behave? How many times will my connection be created?
How many times will my connection be created?
There will be one connection, because "db.js" runs only once. The things you export get stored (module.exports) and that gets returned by every require("./db"). To verify:
require("./db") === require("./db") // true

Trying to GET json data, getting "not a function" error

I'm creating a programmer job board app and I'm trying to display json data on my main page. At some point I'll render it, but for now I'm just trying to get it to show up in json form so that I know it works.
I'm able to connect to the server, but when I load the page I get a TypeError (Job.showAllJobs is not a function).
I'm using a crud app I made the other week as a reference, but there are a few differences between it and this project that are throwing me off.
Here's my project's file structure:
job-board
database
connection.js
schema.sql
models
Job.js
User.js
views
index.ejs
login.ejs
server.js
Unlike my previous crud app, this project is using a connection.js file that gave some trouble earlier. At first I thought I was out of the woods, but I think it might be responsible for my current problem.
Not getting GET to work might seem like a minor error, but it's really bugging me and I haven't been able to keep working because of it.
I populated my table (jobs) with a sample listing as a test, but in the very near future I plan on connecting the app to the GitHub jobs api.
server.js:
const express = require('express');
const app = express();
const PORT = 3000;
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
const Job = require('./models/Job');
const User = require('./models/User');
const connection = require('./database/connection')
app.use(bodyParser.json())
app.use(methodOverride('_method'));
const urlencodedParser = bodyParser.urlencoded({ extended: false })
app.set("view engine", "ejs");
///// GET /////
// GET INDEX
app.get('/', (request, response) => {
Job.showAllJobs().then(everyJob => {
response.json('index');
// response.render('index', { jobs: everyJob });
});
});
Job.js
const Job = {};
const db = require('../database/connection');
///// JOBS /////
/// INDEX ///
Job.showAllJobs = () => {
return db.any('SELECT * FROM jobs');
};
module.exports = Job;
module.exports = db;
connection.js
// require database setup to use pg-Promise
const pgp = require('pg-promise')({});
// connection url
const connectionURL = "postgres://localhost:5432/job_board";
// new database connection
const db = pgp(connectionURL);
// module.exports = db;
You have a couple of problems here.
Make sure you're passing the jobs into res.json instead of the string 'index'
Make sure you're exporting db from connection.js
You're exporting both Job and db from Job.js. Since you're exporting db second, it's overriding the export of Job.

nodejs express mongoose connect to db error

I use nodejs express and mongoose to connect mongodb,I've created a config.js in root folder.I am trying to exports db connect in db.js and trying to import in adminController.js
But when I run the server and refresh the browser ,it log me some errors and not log my log in terminal.
config.js
module.exports = {
cookieScret:'ThreeKingdoms',
db:'threekingdoms',
host:'localhost',
port:27017
}
db.js
var mongoose = require('mongoose'),
config = require('../config'),
connection = mongoose.connection;
module.exports = function(mongoose){
return mongoose.connect('mongodb://'+config.host+'/'+config.db);
}
adminController.js
var express = require('express'),
router = express.Router(),
mongoose = require('mongoose'),
mainInfo = require('../models/admin'),
db = require('../models/db');
router.get('/', function(req, res) {
res.render('admin', { title: 'hey im here!how are you' });
db.on('error',console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log(db)
});
console.log(db)
});
router.post('/',function(req,res,next){
//console.log(req.body)
var mainInfo = mongoose.model('mainInfo');
})
module.exports = router;
question files is in red box
terminal error
I am new to nodejs,so please help me,Thanks
First, it seems that you don't have kerberos installed. Please run npm install kerberos.
Also, the line
Can't set headers after they're sent
Suggests you're trying to modify/send the response after it was already sent back to the client, and that's the error you're getting.
finally it is work now,but it doesn't matter with 'kerberos' ,it is i use wrong way to export my module.terminal still log me 'kerberos undefined' but web can work,i think maybe some time i will try to figure this question out.thanks for your attention

Sharing a MongoDB connection with other js files

Using Node.js/Express.js/Monk.js, I'm trying to share my MongoDB connection with other JS files.
In apps.js, I had declared:
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/ta');
module.exports = db;
require('./libs/mylib');
(db works fine)
In /lib/mylib.js I had:
var db = require('db');
But I get the error: Error: Cannot find module 'db'
How can I make this db connection available through all my js libs ? (and is it the right approach?)
In apps.js
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/ta');
module.exports = db;
In /lib/mylib.js
var db = require('../apps.js')
Though i would reccommend making a separate file called db.js and in that file export the connection ,that is more cleaner.

Categories

Resources