omrii
omrii

Reputation: 413

Node.js javascript - call function from external script server-side

I'd like my Node.JS website to send an email every time a form is submitted on the contact-us page.

HTML page

<form class="contact_us_form" method="post">
    <button type="submit" >Submit</button>
</form>

Public.js

router.post('/contact_us', function(req, res, next)
{
   console.log('FORM SUBMITTED FROM CONTACT_US PAGE');
   sendMail();
});

utils.js

function sendMail() 
{
     //function body
}

When I press the submit button on the html then sendMail is being called but it cannot be found, so the html page and the public.js files are linked properly, but public.js and utils.js are not.

How would I go about linking the function "sendMail" to Public.js? This function is meant to run on the server, NOT on the client.

Upvotes: 1

Views: 2041

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073968

NodeJS uses the concept of modules. You'd export sendMail from utils.js:

exports.sendMail = sendMail;

...and import it in public.js:

var sendMail = require("./utils.js").sendMail;

// ...

sendMail(/*...*/);

or:

var utils = require("./utils.js");

// ...

utils.sendMail(/*...*/);

Here's a complete example:

utils.js:

function sendMail() {
    console.log("I'm sending mail now...");
}

exports.sendMail = sendMail;

public.js:

var utils = require("./utils.js");
utils.sendMail();

Running it:

$ node public.js
I'm sending mail now...

Upvotes: 2

Related Questions