3

I am trying to pass function response from one Node.js script to another

Here is what I am trying. Index.js

var express = require('express');

require('./meter');

var app = express();

app.get('/',function(req,res){
    return;                    //hi function from another file
})

app.listen(3000);
console.log('listening on 3000 port')

meter.js

module.exports = {

    hi: function(req, res) {
        return res.status(200).json({"message" : "Hello V1"});
    }
};

does require function only will do the job?

Thanks in advance.

3
  • 1
    Yes. But you will have to export hi in meter.js and you'll have to use it similar to what you've done for express. Commented Nov 12, 2016 at 6:17
  • Thanks @PratikGaikwad. But I get what you are saying but don't know how to do that. Please can you write little code in Answer Commented Nov 12, 2016 at 6:21
  • 1
    please see the answer posted by Nir Levy below. Commented Nov 12, 2016 at 6:23

2 Answers 2

3

When you use require, you should assign it to a variable, and then you can use it in your code:

var express = require('express');
var meter = require('./meter');  // meter will be an object you can use later on
var app = express();

app.get('/',meter.hi); // you actually don't need another annonimous function, can use hi directly as the callback

app.listen(3000);
console.log('listening on 3000 port')
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Nir Levy. Worked perfectly. :)
2

The answer by Nir Levy is correct but I'll try to give you a little more context on what's going on.

var express = require('express');
// Import the meter export and assign it a variable for reuse.
var meter = require('./meter');
var app = express();
app.listen(3000);
console.log('listening on 3000 port')

As per Nir's answer, you'll just use meter.hi for handling get requests to /

app.get('/', meter.hi);

What exactly is happening here is JavaScript passes all the arguments to the meter.hi method. In case of express there will be 3 arguments here - request, response and next passed in that order.

In the module meter you are just using request and response alone, which is fine, but if there's any other processing required or arguments for meter.hi needs to vary you might want to follow the following practise.

app.get('/', function( req, res ) {
  // You can process the request here.
  // Eg. authentication
  meter.hi(req, res);
});

Where you have more control over the arguments being passed to your modules.

Comments

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.