Home > Back-end >  How can I run a node script in a Vite React project
How can I run a node script in a Vite React project

Time:07-07

I am trying to build a little SPA where a user can run a Presto query, I am using a Node presto client. When running the script via node it works without any issues. I am trying to implement it now via Vite

// lib/presto.js

import {Client} from 'presto-client'

const client = new Client({
  host: 'lga-xxx-adhoc.xxx.com',
  ssl: {
    rejectUnauthorized: true,
  },
  ...

  function getPrestoData(query) {
  return new Promise((resolve, reject) => {
    client.execute({ ...

This is how I currently have it set up. When running the script via a React FE like so..

// App.jsx
import {getPrestoData} from './lib/presto'

function App() {
  const [data, setData] = useState([])

  const getData = async () => {
    await getPrestoData(query)
      .then(data => setData(data))
      .catch(error => console.log(error))
  }
  ...

I am getting an error in the browser like so index.js:4 Uncaught ReferenceError: __dirname is not defined

I have "type": "module", in my package.json but I have also tried the following var presto = require('presto-client'); but in the browser I get required is not defined.

Therefore is it possible to run a node script like this, and if so how. This is how my src folder is

├── src
│   ├── App.jsx
│   ├── favicon.svg
│   ├── index.css
│   ├── lib
│   │   └── presto.js
│   ├── logo.svg
│   └── main.jsx
├── tailwind.config.js
└── vite.config.js

CodePudding user response:

Vite is a frontend toolkit, it does not execute backend code, for that you would have to send a request to your backend

// App.jsx
function App() {
  const [data, setData] = useState([])

  const getData = async () => {
    const response = await fetch('http://mywebsite.com/api/run-presto-query', {
        method: "POST",
        body: // Your query here
    });
    setData(await response.json()); // Assuming you return results in a JSON format
  }

then on your backend you'd have an API route configured that points to a class/function that will execute the query, using a short, (untested) expressJS example.

// server.js

const express = require('express');
const app = express();
const port = 80;

const Presto = require('./lib/presto');

app.post('/api/run-presto-query', (req, res) => {
  res.send(Presto.getPrestoData(req.body.query)); // get the query parameter from the POST body, pass it to the presto client and return its results to the client
});
  • Related