How to call node.js function from browser without framework

I picked a tutorial from the internet with these code:

// calc.js
 
const add = (x,y) => x + y;
const multiply = (x, y) => x * y;
 
module.exports = {
 	add,
 	multiply
 };

and

 // index.js
 
 const cal = require('./cal');
 
 console.log(calc.add(2, 3));
 console.log(calc.multiply(2, 3));

They are good example but how do I call the functions from browser something like this:

 // index.js
 
 const http = require('http');
 const fs = require('fs');
 const calc = require('./calc');
  
 var handleRequest = (request, response) => {
     response.writeHead(200, {
         'Content-Type': 'text/html'
     });
     fs.readFile('./index.html', null, function (error, data) {
         if (error) {
             response.writeHead(404);
             respone.write('Whoops! File not found!');
         } else {
             response.write(data);
         }
         response.end();
     });
 };
  
 http.createServer(handleRequest).listen(8000);

and

  // index.html
 
  < script>
 	console.log(calc.add(2, 3));
 	console.log(calc.multiply(2, 3));
 </ script>

Can this be possible and how? Noted that Content-Type isn’t the issue and the reason I want to do this is because I want to use some require() functions.

If this isn’t possible, what is the way to do it.

Thank you,

It looks like you’re trying to use a function on your page without inserting it into the page itself. You’ll need to include the calc function reference on the rendered page. You can’t call a Node function from within your page without making an AJAX/Fetch call to return a response.

Something like this:

// index.html
<script src="path/to/calc.js"></script>
<script>
 console.log(calc.add(2, 3));
 console.log(calc.multiply(2, 3));
</script>

What you might need to do is update your server to serve any static file instead of just the html file unless you want to host the calc.js somewhere else and reference it that way or include calc.js directly on the page.

var fs = require('fs'),
    http = require('http');

http.createServer(function (req, res) {
  fs.readFile(__dirname + req.url, function (err,data) {
    if (err) {
      res.writeHead(404);
      res.end(JSON.stringify(err));
      return;
    }
    res.writeHead(200);
    res.end(data);
  });
}).listen(8080);

https://nodejs.org/en/knowledge/HTTP/servers/how-to-serve-static-files/

Thank you for the guidance. Yes, I want to host the cal.js somewhere else. It’s just an example.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.