FrankLeeKant
FrankLeeKant

Reputation: 23

How to expose functions in Node app

I have a node express app with a simple html, app.js, helper.js

Running command node app.js works fine and the page appears and operates correctly at localhost:3000.

I want to be able to call functions that exist IN app.js, called FROM helper.js. I've seen several examples in StackO about using module.exports but the examples all call the functions the other way around.

Is there a way (ways) to do this? I've seen a little of browserify that seems promising. Is that the only option?

I know the way this is written won't work, but could something like this be done? Such that if I clicked a button in the web page it will console '3.14'?

app.js

// Various  lines of node and express code
module.exports = {iLikePi: function() { return '3.14' } }

helper.js

var app_mod = require('./app.js')
function aButtonClicked() { console.log(app_mod.iLikePi()) }

index.html

// A button onclick event that calls aButtonClicked() 

And finally, the reason for all this. I am trying to use sqlite3 inside a node app. The only way I can require sqlite3 into a module seems to be in the app.js. It doesn't work when I try to require sqlite3 into helper.js. If there was a way to write a module outside of app.js that can call and use the npm's sqlite3 then that would be an alternative that would be just fine for me!

Thanks everyone, Frank

Upvotes: 0

Views: 1708

Answers (2)

FisNaN
FisNaN

Reputation: 2865

Your client-side code should never access the SQL server directly. You can expose your data through either an API call / HTTP request or to a certain route.

A client-side POST example:

onButtonClick = () => {
  fetch("/math/executepifunc", {
    method: "POST",
    redirect: "follow",
    headers: {
        "Accept": "application/json",
        "Content-Type": "application/json"
    },
    body: JSON.stringify({ 
      num: <value> // something your want server to do with the Pi
     })
}).then(response => {
    // Process your response there
}).catch(err => {throw err;});
}

From server:

// Mini-middleware grabs all routes under "/math"
var mathFuncRouter = express.Router();
router.post("/executepifunc", (req, res) => {
  const num = req.body.num;
  // execute your function from server
});

// Connect to your custom middleware
app.use("/math", mathFuncRouter);

Upvotes: 0

Alex K
Alex K

Reputation: 890

You can definitely call functions from another file!

Here is an example:

app.js

const iLikePie = () => 3.14

module.exports = iLikePie

helper.js

const app_mod = require('./app.js)

const aButtonClicked = () => console.log(app_mod())

This will print 3.14 when aButtonClicked is called.

Upvotes: 1

Related Questions