使用 module.exports 来导出模块(导出的只能是对象或函数)
module.exports = { abc: abc, fn: fn }
// 导入模块(基本上和之前加载模块一样) const bbb = require(‘./bbb.js‘); // console.log(bbb); // { abc: ‘hello‘, fn: [Function: fn] }
mysql操作流程是固定的,尤其是前三步。将前三部封装到一个模块,导出链接对象。 链接对象就可以调用query方法执行sql语句,也能执行end方法关闭链接 // 封装 mysql 查询的代码;并导出模块 function abcd (sql, values, cb) { const mysql = require(‘mysql‘); const conn = mysql.createConnection({ host: ‘localhost‘, port: 3306, user: ‘root‘, password: ‘‘, database: ‘yingxiong‘, multipleStatements: true }); conn.connect(); conn.query(sql, values, cb); conn.end(); } // 导出模块(只能导出 对象和函数 ) module.exports = abcd;
test.js中可以测试一下
// 加载db.js const db = require(‘./db.js‘); // db 是一个函数 db(‘select id, name from heroes limit 2‘, null, (err, result) => { if (err) throw err; console.log(result); });
原文:https://www.cnblogs.com/star-meteor/p/12790910.html