Calling custom function from server.js

Does anyone know how to invoke a custom function in a separate file from the server.js?

My setup is I have this single extra file, hello.js, with a single function, hello(), that I’m trying to call from server.js. I’ve tried the following in server but it doesn’t work:

const express = require("express");
const hello = require("./public/hello.js");   // <-- where I try to include custom file
const app = express();

app.use(express.static("public"));
app.use(hello);

app.get("/", function(request, response) {
  response.send(request.hello());
});

// listen for requests :)
const listener = app.listen(process.env.PORT, function() {
  console.log("Your app is listening on port " + listener.address().port);
});

For completeness, hello.js just contains this:

function hello() {
   return "greetings, traveler";
}

Hi @Suds-p, its very helpful that you’ve shown your attempt.

What errors are you getting from the server Log?

If the hello code is only to be run on the server, it’d be better to have it outside of the public folder, because everything in public is served to the client if requested.

As you are using node’s require function, the hello.js will need to behave as a node module, and export the functions it is sharing. Add the following at the end of hello.js

module.exports = hello;

For more info, here are the docs for node modules https://nodejs.org/api/modules.html

To use the function as express middleware, it needs to have parameters such as

function (req, res, next)

Here is the docs for creating express middleware http://expressjs.com/en/guide/writing-middleware.html

1 Like

Thank you so much for your reply! I apologize I took this long to test it out, and I thought I was close to having all the right pieces in place, but for some reason the server decided to quit working and now it will not load at all.

(adding link here in case a moderator can take a look at it?)