• Home
  • Jobs
  • Courses
  • Questions
  • Teachers
  • For business
  • ES/EN

0

43
Views
How to correctly call a function from Node.JS to Express.JS

I have a completed script that acts as a parser. The script is written in NodeJS and it works properly. The script returns an array of data and also saves it to my computer. I would like to run this script from the frontend, at the click of a button. As far as I understand, I have to send a request to the server? It's suggested to use Express for the server, but I still haven't figured out how to call a third-party script from it, much less return any data from it. Right now all I want is for my script to run when I make a request for the root directory "/" and send me a json in response (or for example a json file)

    const express = require('express')
    const runParser = require("./parser");
    const app = express()
    const port = 3000
    

    
    app.get('/', async (req, res,next) => {
      await runParser()
        next()
    })
    
    app.listen(port, () => {
        console.log(`Example app listening on port ${port}`)
    })
about 1 month ago ·

Juan Pablo Isaza

1 answers
Answer question

0

All you need for Express is this:

const express = require('express');
const app = express();
const runParser = require("./parser");
const port = 3000;

app.get("/", (req, res) => {
   runParser().then(results => {
      res.json(results);
   }).catch(err => {
      console.log(err);
      res.status(500).send("error");
   });
});

app.listen(port, () => {
    console.log(`Server running on port ${port}`);
});

And, then you can access that either by just going to:

http://localhost:3000

from your local host or

http://yourdomain.com:3000

in the browser or by issuing an ajax call to the desired URL from webpage Javascript.


I wouldn't personally put this type of activity on a GET request to / because that can be hit by things like web crawlers, search engines, etc...

It probably belongs on a POST (so crawlers won't issue it) and I'd personally put it on some pathname such as:

app.post("/runparser", (req, res) => {
    // put your code here
});

And, then use a form submission or ajax call to that URL to trigger it.

about 1 month ago · Juan Pablo Isaza Report
Answer question
Find remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.