9

I have mysql connection code which I need to call each time in every .js file. Say I want sql.js from main.js. I am thinking include(sql.js) ?

 sql.js

 var sql = require('sql');
 var connection = sql.createConnection({
 host : 'localhost',
 user : 'root',
 password : '',
 database : 'db'
 });

connection.connect(function(err){
if(!err) {
console.log("connected");
}
jeny
  • 367
  • 4
  • 6
  • 17

2 Answers2

13

You can create a module, and require it the following way.

File A: sql.js

var a = function a(){

};

module.exports.a = a;

Files B, C, D:

var sql = require("./sql");

sql.a();
Pavel
  • 1,278
  • 2
  • 17
  • 34
0

require.

for example var sql = require('sql.js');

you need in the sql.js to return an object at the end with module.exports = myobj;

Example:

module.exports = {
 sql_connection: null,
 connect: function() {
    // connect to db
   this.sql_connection = ... ; // code to connect to the db
 }

};
  • 1
    In some scenarios, it is required to specify a path in the `require` function (i.e. './sql.js') in order to be recognized, as in @Pavel 's example – Jaime Jul 05 '16 at 08:39
  • It depends if package.json is configured correctly i think, but yes if you don't use "./" it won't search in the current folder. It is better to use `require(__dirname + './script.js')` in order to execute the script from where you want. – Pierre Emmanuel Lallemant Jul 05 '16 at 09:34
  • @PierreEmmanuelLallemant that is redundant. __dirname is the same as `./`. I don't code Js, so if that is the actual way they do it, then that's just one more reason to hate Js. – Ryan Dec 06 '19 at 22:49