Passing a JSON from another js file with Express and EJS

I am working on a project to manage printers with CUPS command-line, I have multiple "api’s" that make different thinks, for now i just want so see my parsed JSON result in a view, but I’m clueless on how to pass that value trough Express and then render it in a EJS view:

my api:

const spawnSync = require("child_process").spawnSync;
const parseStdout = require('../utils/utils.js');

function lpstat(){
let printerList = spawnSync("lpstat -p", {
    timeout: 10000,
    encoding: "utf-8",
  });
 
  let parsedList = parseStdout(printerList);
  
  let onlyPrinterList = parsedList.filter(function (line) {
    return line.match(line.match(/^printer/) || line.match(/^impressora/));
  });
  
  let onlyPrinterNames = onlyPrinterList.map(function (printer) {
    return printer.match(/(?: \S+)/)[0].trim();
  });
  process.on('exit', (code) => {
    process.kill();
  });
  //this is what i want to pass to the view
   return JSON.stringify(onlyPrinterNames);
}

my app.js

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

app.listen(3000);
app.set('view engine', 'ejs');


app.get('/lpstat',(req,res) => {
//what should i use here?
    res.render('lpstat')
});

my lpstat.ejs

<html lang="en">
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>lpstat</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
</head>
<body>
    <p>lpstat result:</p>
   <%= what should i use here?%>
</body>
</html>

1 thought on “Passing a JSON from another js file with Express and EJS”

  1. The second parameter in res.render defines the data that is given to your templates:

    app.get('/lpstat',async (req,res) => {
        // Call your api here to fill the variable
        const printers = await callApi()
        res.render('lpstat', {
           printers
        })
    });
    

    You will be able to use this in your ejs template then

    <p>lpstat result:</p>
    <%= printers %>
    

    You will need to replace callApi with whatever function is used to fetch your data. I used async/await for a simpler answer, can be done with callbacks as well.

    Reply

Leave a Comment