How do I call .js from another .js file? [duplicate]

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");
}

Answers:

Answer

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();
Answer

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
 }

};

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.