user1354743
user1354743

Reputation: 417

Node.js functions

I use node.js with the express framework and I have figured out how the routing works.

app.get('/save',webcalender.save);

I have a webcalender file with this function:

exports.save = function(req, res){
res.send(req.query["headline"]);};

But how would I built a different function and use it in there:

exports.test = function() { console.log("test"); }

I have tried:

exports.save = function(req, res){
    test(); or webcalender.test or also test = webcalender.test(); and then test;
res.send(req.query["headline"]);};

thanks for you help

Upvotes: 0

Views: 705

Answers (1)

Dmitry Kudryavtsev
Dmitry Kudryavtsev

Reputation: 17584

This question is a bit unclear.

I assume save function is defined in some webcalendar.js and imported with

var webcalendar = require('./webcalendar.js');

Ill break the answer now in two scenarios.

Assuming test function is the same webcalendar.js

You can then do something like

var test = function() {console.log("test");}
exports.test = test;

Or in one line

var test = module.exports.test = function() {console.log("test");}

And then to use test in the same module simply call test(); like you did.

In case if test is defined in another module

Lets say in test.js then in order to use it in webcalendar.js module you have to require it like this:

var test = require('./test.js').test;
exports.save = function(req, res){
    test();
res.send(req.query["headline"]);};

or simply

exports.save = function(req, res){
    require('./test.js').test();
res.send(req.query["headline"]);};

This should cover most of the cases, if its not please clarify your question since as I said earlier its unclear.

Also I suggest you to familiarize your self with nodejs module to understand why, what and when you need to export, since its not clear from you question why are you exporting the test function (in case if its used only in webcalendar.js module). Here is another good resource to nodejs require

Good luck!

Upvotes: 2

Related Questions