Search code examples
node.jsexpressnode-mysql

Can I store SQL statements in a separate file in node js?


I would like to store all my SQL statements in a separate (.txt maybe?) file. This will make my code look clean and more readable.

Example:

router.get('/', function (req, res, next) {

var sql = // get SQL from a file

connection.query(sql, function (err, rows, fields) {
    var row;

    if (!err) {
        row = rows[0];
    }

    res.render('index', { ... });
})

}); 

P.S. I don't want to store the SQL statements in a .js file.

Thank you in advance


Solution

  • You surely can do that but remember that work with files cost "too much time". What you probably need is a layer that do that queries.

    For example you could do something like:

      myDBLayer.getNumber(function(id, country, name){
        //Do stuff
      });
    

    But you have to define the getNumber function and do a function for every query you want. Off course you can receive parameters and be a kind of abstract with that but I think that is more efficient that just read some file with all queries.