T
T
titronfan2016-06-02 18:24:07
JavaScript
titronfan, 2016-06-02 18:24:07

How to export a module in Node.js?

Hello!
There are 2 files (index.js which runs the whole application and func.js).
You need to export the func.js file as a module in index.js.
I am doing this now (everything works), although I understand that this is not true.
Simplified:
index.js

var express = require('express');
var mysql = require('mysql');
var funcs = require('./func');

var app = express();

// DB
var db = mysql.createConnection({
  host     : 'localhost',
  user     : 'usr',
  password : '123',
  database : 'customers'
});
db.connect();

app.use(funcs);

app.get('/customer', function (req, res) {
  db.query('SELECT id, name FROM customers WHERE id='+ req.query.id, function(err, row, fields) {
      if (!err) {
        res.send(row[0]);
      }
      else {
        console.log(err);
      }
    }
  );
});

func.js
var express = require('express');
var mysql = require('mysql');

var app = express();

// DB
var db = mysql.createConnection({
  host     : 'localhost',
  user     : 'usr',
  password : '123',
  database : 'customers'
});
db.connect();

module.exports = app;

app.get('/users', function (req, res) {
  db.query('SELECT id, name FROM users WHERE id='+ req.query.id, function(err, row, fields) {
      if (!err) {
        res.send(row[0]);
      }
      else {
        console.log(err);
      }
    }
  );
});

app.get('/users-other', function (req, res) {
  db.query('SELECT id, name FROM users_other WHERE id='+ req.query.id, function(err, row, fields) {
      if (!err) {
        res.send(row[0]);
      }
      else {
        console.log(err);
      }
    }
  );
});

Please help with advice or an example of how to make it so that in the func.js file you do not need to connect the express and mysql
modules again . Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
titronfan, 2016-06-02
@titronfan

I did it on the advice of Vladlen Ultra .

var express = require('express');
var app = express();
require('./func')(app);
app.listen(3000);

app.get('/customer', function (req, res) {
  res.send('customers!');
});

module.exports = function (app) {

    app.get('/', function (req, res) {
        res.send('none!');
    });

    app.get('/user', function (req, res) {
    res.send('users!');
    });

    app.get('/users', function (req, res) {
    res.send('users others!');
    });

};

But still in doubt .. is it true or not.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question