AttackTheWar
AttackTheWar

Reputation: 219

NodeJS Middelware/Routing Data transfer

Hello i'm trying to transfer more data to the client. I have used sample code for the middleware in NodeJS express.

I want to read 2 different files and transfer the data to the client. I have managed to transfer 1 file data. How can I add multiple?

how should I do this?, I have tried 'send' and 'json' but then I cant see my front end of the website

var express = require('express');
var router = express.Router();
const fs = require('fs');

/* GET home page. */

// const myHtml = require('fs').readFileSync(<path to html>);
const myHtml = fs.readFileSync('./views/index.html', 'utf-8');

//Data from server to client, this works.
const myJson = fs.readFileSync("./apidata.json", 'utf-8');

//I want to add a second one here
const apisparkline = fs.readFileSync("./apisparkline.json", 'utf-8');


console.log("server is running");


router.get('/', function(req, res, next) {
  //This works perfect
  res.end(myHtml.replace(/jsonapidata/g, JSON.stringify(myJson, '', 2)));


  //how should I do this?, I have tried 'send' and 'json' but then I cant see my front end of the website
  res.end(myHtml.replace(/sparklinedata/g, JSON.stringify(apisparkline, '', 2)));
});

module.exports = router;

Upvotes: 1

Views: 30

Answers (1)

Vishnudev Krishnadas
Vishnudev Krishnadas

Reputation: 10960

Simply use,

res.end(myHtml.replace(/jsonapidata/g, JSON.stringify({myJson,apisparkline}, null, 2)));

Better way,

res.json({myJson,apisparkline})

and then, format at client.

Upvotes: 1

Related Questions