lundi 30 mars 2015

How can I require the module into my file?

I create an express project and the directory structure like:



/
- model
db.js
- routes
users.js
app.js


In ./model/db.js, I have a MySql connection:



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

connection.connect();


And in ./routes/users.js, I need to query database:



var express = require('express');
var router = express.Router();
var db = require('./model/db.js'); // always cannot find the module....

router.route('/')
.get(function (req, res) {
connection.query(
'select * from user',
function (err, rows, fields) {
if (err) {
res.status(500).send('error');
} else {
res.send({
result : 'success',
err : '',
err_type : '',
fields : fields,
rows : rows,
length : rows.length
});
}
}
)
});


module.exports = router;


But the debugger always says that Cannot find the module './model/db.js'.


I am new to nodejs, can anybody tell me how to require the db.js into routes file? Thanks a lot.


Aucun commentaire:

Enregistrer un commentaire