2

I have a big app.js file and want to split the code. I took all my routes into a module called routes.js

module.exports = function(app){

app.get('/', function (req, res) {
  res.redirect('/page1');
});

app.get('/page1', function (req, res) {
  res.render('page1');
});

app.get('/page2/:id', function (req, res) {
    res.render('page2', {
      val: Number(req.params.id)
    });
});

}

and in my app.js I call

const routes = require('./Server/routes')(app);

So this works fine.

I have some functions like

function loadData(id, callback) {
  fs.readFile('./database.json', 'utf8', function (err, data) {
    var json = JSON.parse(data);
    var arr = json.arr;
    var obj = arr.find(e => e.id === Number(id));
    callback(obj);
  });
}

and want to have them in separate files too. How can I do this? I am able to export one function but how can I export more than one?

Like

module.exports = function(){

function sayHello(){
   console.log("Hello");
}

function calc(){
   return 5 + 7;
}

}

require the module and call

myModule.sayHello();

var num = myModule.calc();
2
  • 1
    Here you go. Let me know if this is what you asked for. Commented Nov 29, 2017 at 8:03
  • I think so, is this correct? hastebin.com/unobutifem.js Commented Nov 29, 2017 at 8:07

1 Answer 1

3

In your new module you can export an object and define your functions inside object

module.export = {
    sayHello: function() {
        console.log("Hello");
    },
    calc: function() {
        return 5 + 7;
    }
}

// usage: const mymodule = require('path/to/your/file');

also you can export a function and define your needed functions in prototype

function mymodule(someArgsIfNeeded) {
    // do some initialization
}

mymodule.prototype.sayHello = function() {
    console.log("Hello");
}
mymodule.prototype.calc = function() {
    return 5 + 7;
}

module.export = mymodule

// usage: const mymodule = require('path/to/your/file')(someArgsIfNeeded);
Sign up to request clarification or add additional context in comments.

1 Comment

ah okay, this syntax is new to me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.