Error in parsing json array accepting multiple values - json

Whenever i am giving a single data element in my json file my code works fine,but as soon as i give an array of elements it starts showing undefined on the client side.
This is my server side code.
var app = require('express')()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
var fs= require('fs');
server.listen(3000);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/cli_index.html');
});
io.sockets.on('connection', function (socket) {
var file = __dirname + '/data.json';
fs.readFile(file, 'utf8', function (err, data) {
if (err) {
console.log('Error: ' + err);
return;
}
data = JSON.parse(data);
// You can save those values somewhere or just log them to the console
console.log(data);
socket.emit('news', { hello: data});
});
});
This is my client side code.
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
JSON.stringify(data);
for(var i=0;i<2;i++){
document.write(data[i].hello.name);
}
});
</script>
This is my external json file.
[{"name":"hey"},{"name":"Gouraw"}]

In this server side code:
socket.emit('news', { hello: data});
...you're sending the array as the hello property of an object, but this client-side code:
document.write(data[i].hello.name);
...is expecting the top-level to be an array, with individual hello properties for each entry. Change that to:
document.write(data.hello[i].name);
...so you're indexing into the array.
It would probably be best, as well, to limit your loop using the array's length rather than a hardcoded value:
for(var i=0;i<data.hello.length;i++){

Related

How do I save Firebase JSON data into a variable in Node.JS

I've figured out how to save and retrieve date from Firebase but, I am having problems savings the JSON into a variable. I have set the variable to usersDB but, when I console.log() the variable, It logs out as undefined
//firebase setup
var db = admin.database();
var ref = db.ref("server/saving-data/fireblog"); //var for databaseURL
//firebase
var usersRef = ref.child("users"); //where I am pulling the data from
var usersDB // init var
ref.on("value", function(snapshot) {
console.log(snapshot.val()); // logs the way I want it
usersDB = snapshot.val(); // trying to save json
}, function (errorObject) {
console.log("The read failed:" + errorObject.code);
})
console.log(usersDB) // logs undefined
app.get("", function(req, res) {
res.render("index", {users : usersDB});
})
app.post("/", function(req, res) {
console.log(req.body.user.username);
usersRef.child(req.body.user.username).set({
name: req.body.user.name,
email: req.body.user.email,
});
res.redirect('/');
});
Try passing the variable into another function and save it there:
ref.on("value", function(snapshot) {
console.log(snapshot.val()); // logs the way I want it
func_(snapshot.val()); // trying to save json
}, function (errorObject) {
console.log("The read failed:" + errorObject.code);
})
function func_(json){
console.log(json) // logs undefined
}

Render JSON data onto ejs view with Expressjs

I am trying to get 2 values from a JSON file on to the webpage.
obj["fruit"] and obj["thyroid"]. I use ejs as the template view engine and expressjs.
The below method says "fruit" and "thyroid" are undefined. The console.log works though.
app.post('/top', function (req, res) {
var obj;
fs.readFile('./object.json', 'utf8', function (err, data) {
if (err) throw err;
obj = JSON.parse(data);
console.log(obj["fruit"]);
console.log(obj["thyroid"]);
});
res.render(
'disp.ejs',
{
food: obj["fruit"]
name: obj["thyroid"]
}); // render
});
fs.readFile(path[, options], callback) is the asynchronous way to read a file. The way your code is setup node will start reading the file and immediately then call res.render before the file data is finished reading.
If you put the res.render inside the callback it will only be called when the file is finished reading and the data variable has what you need.
for example:
app.post('/top', function (req, res) {
var obj;
fs.readFile('./object.json', 'utf8', function (err, data) {
if (err) throw err;
obj = JSON.parse(data);
console.log(obj["fruit"]);
console.log(obj["thyroid"]);
res.render(
'disp.ejs',
{
food: obj["fruit"]
name: obj["thyroid"]
}); // render
});
});

show json data in index file

I dont understand why I cant display my json data. I am new to javascript and I want to display the data in the json file to my index file.
I have used the express generator for all the files. I did read that I should add this FS code in my app.js, but I cant use the data variable in my index file in my view. Any help ?
var express = require('express');
var router = express.Router();
var fs = require('fs');
/* GET home page. */
router.get('/', function(req, res, next) {
var file = __dirname + '/public/list/list.json';
var data;
fs.readFile(file, 'utf8', function (err, data) {
if (err) {
console.log('Error: ' + err);
return;
}
data = JSON.parse(data);
console.log(data);
});
res.render('index', { title: data });
console.log(data);
});
module.exports = router;
here is my json file
{
"username":"xyz",
"password":"xyz#123",
"email":"xyz#xyz.com",
"uid": 1100
}
fs.readFile is asynchronous , so you should put res.render(..) inside his callback , because it will fired when the readFile function ends. So change your code to :
fs.readFile(file, 'utf8', function (err, data) {
if (err) {
console.log('Error: ' + err);
return;
}
data = JSON.parse(data);
console.log(data);
res.render('index', { title: data });
});
The above answer is correct, but there's also an alternative.
If you're using this file for your index page, it'd be used a lot. If the data isn't changing, you can simply require the JSON file at the top of your code and return it in the request.
var express = require('express');
var router = express.Router();
var list = require(__dirname + '/public/list/list.json');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: list });
});
module.exports = router;
However, if that data does change frequently, reading the file is the way to go.

Serving HTML file from Node server

Pretty much purely for pedagogical purposes, I'm serving both my front and back end data out of my one node server. Right now, I'm at the point where I've received my client request successfully, created some data based on said request, am able to console log it, etc. Everything is fine up to that point. My issue is that in the event that my data is only an html file, which is being read with the fs library, it will not render on the page when I attempt to serve it out in my res.end() or res.write(). I can see it's exactly what I want and expect when I console log it, but it just doesn't render in the browser. Any help would be appreciated. I've got it set up to where I'm handling my requests in an "if/else" wherein I only have the two scenarios of "/" (home), in which case I serve the html file, and anything else because the server really only needs to handle those two events. Thanks in advance.
Edit. This is what I have so far:
function responseHandler(req, res) {
res.writeHead(200, {"Content-Type": "text/html"});
if (req.url.match("fav")) {
res.end("");
return;
}
else if (req.url.match("/endpoint")) {
var input = req.url.match(/endpoint\/(.*)/)[1];
var output = endpoint.toHTML(decodeURI(input));
res.end(data);
console.log(input, req.url)
}
else {
fs.readFile("index.html", "utf8", function(err, data) {
console.log("data:" + data);
var input = req.url.match(/endpoint\/(.*)/)[1];
var output = endpoint.toHTML(decodeURI(input));
});
}
res.end();
}
I can see the data in the console which, in the last case, is just my HTML file. It just won't render in the page.
How did you attempted to serve the html with res.end() and res.write() ?
I just made a small test here, and this works:
app.js
var http = require('http');
var fs = require('fs');
var html = fs.readFileSync('hello-world.html');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(html);
}).listen(8000);
hello-world.html
<h3>Hello World</h3>
Edit: To match with your code, try this:
function responseHandler(req, res) {
res.writeHead(200, {"Content-Type": "text/html"});
if (req.url.match("fav")) {
res.end("");
return;
} else if (req.url.match("/endpoint")) {
var input = req.url.match(/endpoint\/(.*)/)[1];
var output = endpoint.toHTML(decodeURI(input));
console.log(input, req.url);
// we have no data variable in this scope
res.end("");
// I added a return statement in each step
// Just to be clear that we don't want to go if any
// condition have fit, since we cannot call res.end()
// more than once
return;
} else {
fs.readFile("index.html", "utf8", function(err, data) {
// error handling
if (err) return res.end(err);
// now we have the data
console.log("data:" + data);
res.end(data);
});
return;
}
}
Serving html in asynchronous way works something like that;
var fs = require('fs');
var http = require('http');
http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/html'});
fs.readFile('index.html', function(err, data){
if(err){
return console.log(err);
}
res.end(data);
});
}).listen(8080);
console.log('Server is running on Port: 8080');

how to print json array in html return by node.js

i return the array from node.js
reading xml content from txt file and store in array send to html page using ajax method how do this task.
xml2js = require('xml2js');
fs = require('fs');
var arr={};
var parser = new xml2js.Parser();
fs.readFile('D:/test.txt', function(err, data) {
parser.parseString(data, function (err, result) {
arr=result.Cluster.Array[0].String;
});
});
app.get('/test', function(req, res, next) {
res.json({ message: arr }); //passing array data
});
how to display in html page current i used. But i get whole data in console log not able to display in html page get message undefined :
$.ajax({
url: '/test',
complete: function(data) {
JSON.stringify(data);
console.log(data.message);
// document.write(data.message);
for(i=0;i<data.length;i++)
{
document.write(data.message[i].Val);
$('#did').append('<h1>'+data.message[i].Name+'</h1>');
}
}
use a ReadStream, and stream it into your httpResponse
stream = fs.createReadStream "path/to/file.json"
stream.pipe(res)