0

I have an array variable in my node.js file.I am trying to display the values of this array in a tabular form on my html front end page.So how can I send this array variable to jquery/javascript so that I can append like this $('body').html(string).

out.txt

IMAGE                  STATUS        NAMES
k8s.gcr.io/pause:3.1   Up 2 days     k8s_POD   Deploy  Decomission Properties
eb516548c180           Up 2 days     k8s_cor   Deploy  Decomission Properties


index.js

var fs = require('fs');
fs.readFile('out.txt', function(err, data) {
    if(err) throw err;
    var array = data.toString().split(/\s+/);
    for(i in array) {
        console.log(array[i]);
    }
});

trying to do something very similar to the below mentioned code but with the node.js array variable present in the index.js file.

var html = '<table class="table table-striped">';
  $.each(data, function(index, value){
         html += '<tr>';
        $.each(value, function(index2, value2){
            html += '<td>'+value2+'</td>';
        });
        html += '<tr>';
     });
     html += '</table>';
     $('body').html(html);

How can I modify my code accordingly to send the array variable from index.js to frontend javascript or jquery.I think I have to use ajax for this.And once the variable is sent how will I $('body').html or append it to my html page in tabular fashion.Kindly Help.

Vignesh Swaminathan
  • 319
  • 1
  • 9
  • 24
  • I presume you have a node server that loads your client that contains the jquery snippet that you are showing. Perform a HTTP call from your client app that will hit an endpoint on your server that will contain data that you want. Changes should be done both on client and server. – emcee22 Aug 21 '19 at 18:24

1 Answers1

0

Since you are using an array of strings in the success callback you are trying to iterate on the value but it is an string not another array. You did not specified the content of out.txt so I assumed it was somehting like:

out.txt

test1 test2 test3 test4

I included the code for reading the file on a very simple server: Calling http://localhost:3000/ will result on ['test1','test2','test3','test4']

server.js

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

const hostname = '0.0.0.0';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'application/json');
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');
  fs.readFile('out.txt', function(err, data) {
    if(err) throw err;
    var array = data.toString().split(/\s+/);
    res.end(JSON.stringify(array));
    });

});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

I changed the HTTP GET success callback because you have an array of strings so the content of value is the string itself not another array of strings, no inner foreach is required.

index.html

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $.get("http://localhost:3000", function(data, status){
    var html = '<table class="table table-striped">';
    $.each(data, function(index, value){
           html += '<tr>';
           html += '<td>'+value+'</td>';
           html += '</tr>';     
        });
     html += '</table>';

     $("#content").append(html);
    });
  });
});
</script>
</head>
<body>
    <div id="content"> </div>
    <button>GET Data</button>
</body>
</html>

UPDATE

Serving the html file on the server.

server.js

var express = require("express");
var fs = require("fs");
var app = express();
var path = require("path");
app.get('/',function(req,res){
   res.sendFile(path.join(__dirname+'/index.html'));
   //__dirname : It will resolve to your project folder.
});

app.get('/out', function(req,res){
    fs.readFile('out.txt', function(err, data) {
        if(err) throw err;
        var array = data.toString().split(/\s+/);
    res.type('json')
        res.end(JSON.stringify(array));
    });
});

app.listen(3000);
console.log("Server running at Port 3000");

index.html

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){

    $.get("/out", function(data, status){
        var html = '<table class="table table-striped">';
        $.each(data, function(index, value){
            html += '<tr>';
            html += '<td>'+value+'</td>';
            html += '</tr>';     
        });
        html += '</table>';
        $("#content").append(html);
    });
});
</script>
</head>
<body>
    <div id="content"> </div>
</body>
</html>

UPDATE

With the new provided out.txt

server.js

var express = require("express");
var fs = require("fs");
var app = express();
var path = require("path");
app.get('/',function(req,res){
   res.sendFile(path.join(__dirname+'/index.html'));
   //__dirname : It will resolve to your project folder.
});

app.get('/out', function(req,res){
    fs.readFile('out.txt', function(err, data) {
        if(err) throw err;

        const array = [];
        var lines = data.toString().split('\n').filter((column) => column.length != 0);

        for(i=0; i<lines.length; i++) {
             array.push(lines[i].split('  ').filter((column) => column.length != 0))        
    }
    const response = {headers:array[0], rows:array.slice(1, array.length)}; 
        res.type('json')
        res.end(JSON.stringify(response));
    });
});

app.listen(3000);
console.log("Server running at Port 3000");

index.html

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){

    $.get("/out", function(data, status){
        var html = '<table class="table table-striped">';
    html += '<tr>'; 
    $.each(data.headers, function(index, value){            
            html += '<th>'+ value+'</th>';     
        });
    html += '</tr>';
        $.each(data.rows, function(index, line){
            html += '<tr>';
        $.each(line, function(index, value){        
                html += '<td>'+ value+'</td>';
            })
            html += '</tr>';     
        });
        html += '</table>';
        $("#content").append(html);
    });
});
</script>
</head>
<body>
    <div id="content"> </div>
</body>
</html>

UPDATE

Using the output of docker ps instead of an output file.

server.js

var express = require("express");
var fs = require("fs");
var app = express();
var path = require("path");
app.get('/',function(req,res){
   res.sendFile(path.join(__dirname+'/index.html'));
   //__dirname : It will resolve to your project folder.
});

app.get('/out', function(req,res){
const {execSync} = require('child_process');
let output = execSync("docker ps -a --format 'table {{.Names}}\\t{{.Status}}\\t{{.Image}}'", { encoding: 'utf8'});

     const array = [];
     var lines = output.toString().split('\n').filter((column) => column.length != 0);

     for(i=0; i<lines.length; i++) {
         array.push(lines[i].split('  ').filter((column) => column.length != 0))        
     }   
     const response = {headers:array[0], rows:array.slice(1, array.length)};    
     res.type('json')
     res.end(JSON.stringify(response));      
});

app.listen(3000);
console.log("Server running at Port 3000");
vladwoguer
  • 951
  • 1
  • 14
  • 28