How do I call .js from another .js file? [duplicat

2020-04-07 05:01发布

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

2条回答
家丑人穷心不美
2楼-- · 2020-04-07 05:48

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
 }

};
查看更多
Viruses.
3楼-- · 2020-04-07 05:51

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();
查看更多
登录 后发表回答