How to render an array in an html file? - Node.js, ejs - javascript

I'm working on a project, which will use given coordinates from a txt file and graph them.
My problem right now: I'm trying to use ejs to render the coordinates into my html file, but it just isn't working right. Ejs always just renders: undefined.
Here is the code:
var http = require('http'),
fs = require('fs'),
express = require('express'),
app = express();
app.use(express.bodyParser());
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(express.static(__dirname + '/public'));
//Readerfunction
function readLines(input, done) {
//.....
function done(arr) {
var obj = {};
var key1 = arr[0][0];
var key2 = arr[0][1];
obj[key1] = [];
obj[key2] = [];
arr.shift();
arr.forEach(function (item) {
obj[key1].push(item[0]);
obj[key2].push(item[1]);
});
console.log('X:', obj[key1]); // all the variables are logged correctly.
console.log('Y:', obj[key2]);
app.get('/', function(req, res) {
res.render('graph.html', {cordinates: obj});
});
app.listen(8080, function() {
console.log('Server running at http://127.0.0.1:8080/');
});
}
In the html file:
<%= cordinates.obj %>
I hope you can help me, solve this problem! :-)
Greetings,
JS

Well, I think here is the problem: you are passing obj to render as coordinates, so you should use coordinates variable in your template directly, no it's obj property, which is non-existent. I'm not sure if it will be rendered as proper array though, maybe you'll need a loop to print it's elements.

Related

how to render (or pass) 2d array[][] to html?

I have a node.js server, and it has an array[][] data by user's file input.
I want to pass it to html page by res.render(), Could you give me advice on how can I do that?
I did search similiar problem but usually they are about rendering array[], not an array[][].
my array[][] data is like this:
dataLogs[0] ={latitude:33.333,longitude:22.222},
dataLogs[1] ={latitude:33.344,longitude:22.255},
dataLogs[2] = {latitude:33.355,longitude:22.277}
(...)
I want to pass these dataLogs[][] to map html page, for making html mark these places.
I tried to use ejs & res.render(), but I think These are not enough.
const ejs = require("ejs");
const express = require('express'),
http = require('http'),
app = express(),
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
var dataLogs = have some 2d array data;
(...)
app.get('/replay', (req,res) =>{
res.render('drawLines.html',{dataLogs:dataLogs});
});
This is drawLines.html page
var dataLogs = <%= dataLogs %>
(...)
var linePath = [
new kakao.maps.LatLng(dataLogs[0].latitude, dataLogs[0].longitude),
new kakao.maps.LatLng(dataLogs[1].latitude, dataLogs[1].longitude),
new kakao.maps.LatLng(dataLogs[2].latitude, dataLogs[2].longitude )
];
//kakao is just kind of API for map interfaces
(...)
dataLogs[x].latitude, longtiude are not possible to read at this code.
Thank you for reading.

Variables between HTML Client and Node.js Server

I just wanna to pass variables from a HTML page to a node js and perform some calculations on the data and get it back to HTML using ejs
After installing ejs :
npm install ejs
I'm trying to pass this variable temp with value 50 "HTML Page":
<html>
<head>
</head>
<body>
My temperature: <%= temp=50 %>
Temp + 10 : <%= total %>
</body>
</html>
and my nodejs server.js:
var http = require('http');
var ejs = require('ejs');
var fs = require('fs');
http.createServer(function(req,res) {
res.writeHead(200, {'Content-Type': 'text/html'});
//since we are in a request handler function
//we're using readFile instead of readFileSync
fs.readFile('index.html', 'utf-8', function(err, content) {
if (err) {
res.end('error occurred');
return;
}
var temp; //here you assign temp variable with needed value
var total = temp+10;
var renderedHtml = ejs.render(content, {temp: temp, total:total}); //get redered HTML code
res.end(renderedHtml);
});
}).listen(8080);
Any help would be appreciated
Thanks in advance.
In your server file, the value of temp is undefined. And so total = undefined + 10 = undefined. Hence both your variables are undefined in the server file.
Try doing this (in the server file):
var temp = 0
var total = 0
In the html file My temperature: <%= temp = 50 %>
Temp + 10 : <%= total = temp + 10 %>
Now it should display the correct value i.e 50 and 60. Hope this helps
You do not need this fs requirement.
All you need to do is :
var express = require('express');
var app = express();
var path = require('path'); //Use the path to tell where find the .ejs files
// view engine setup
app.set('views', path.join(__dirname, 'views')); // here the .ejs files is in views folders
app.set('view engine', 'ejs'); //tell the template engine
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) { // route for '/'
var temp = 50; //here you assign temp variable with needed value
var total = temp+10;
res.render('index', { //render the index.ejs
temp: temp,
total:total
});
});
var server = app.listen(3000, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
HTML (rename to index.ejs):
<html>
<head>
</head>
<body>
My temperature: <%= temp %>
Temp + 10 : <%= total %>
</body>
</html>

How to use a node api

So i have found an api for node https://github.com/schme16/node-mangafox
But i have no idea on how to use it
Lets say that i want to use this
mangaFox.getManga = function(callback){
$.get('http://mangafox.me/manga/',function(data){
var list = {};
data.find('.manga_list li a').each(function(index, d){
var b = $(d);
list[mangaFox.fixTitle(b.text())] = {id:b.attr('rel'), title:b.text()};
});
(callback||function(){})(list);
}, true);
}
What should i do to show the list in the '/' route
This i what i have so far
var express = require('express'),
path = require('path'),
mangaFox = require('node-mangafox');
var app = express();
app.get('/', function(req, res) {
});
app.listen(1337);
console.log('oke');
If some cloud help me understand how this works
app.get('/', function(req, res) {
function renderList(data) {
return Object.keys(data);
res.send(JSON.stringify(list));
}
var list = mangaFox.getManga(renderList);
});
This is the simplest thing I can come up with. You just get the object returned by the module, list its keys, and send back that stringified as your response. Try it out. You'll probably want to replace the renderList with some HTML templating.

Run the script in node.js only after user select file in html

I am using node.js to launch a serve so that my html can communicate with R code. But I am facing a problem on node.js. In my html page, I have a browse selection button, user can use it to choose the data file they want to read into html and node.js will pass the file name to R, so R code will read data from the selected data file and then run the analytics model. But as i only have very basic knowledge of Node.js, so currently, r code would run only when I open the followling link "localhost:3000/vis/rio". So my question is how to make node.js run the R code in background automatically when the data file has been selected. Thank you very much for your help in advance.
Here are my codes:
Javascript-(sending the file name to node.js):
var dataset,availableTags;
function handleFileSelect(evt) {
var file = evt.target.files[0];
$.ajax({ //getting the file name and update to node.js
type:'post',
url:"/getFileName",
data:{filename:file.name}
});
Papa.parse(file, { //papa is a library I used to read csv file
header: true,
dynamicTyping: true,
complete: function(results) {
dataset=results.data;
}
});
}
$(document).ready(function(){
$("#csv-file").change(handleFileSelect);
});
Node.js script:
serve.js:
var express=require('express');
var path = require('path');
var vis = require('./routes/vis');
var index = require('./routes/index');
var bodyParser=require('body-parser');
var app=express();
require('./routes/main')(app);
app.get('/vis/rio',vis.rio); **//this is a package used to get connection with Rserve**
app.set('views',__dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded());
app.post("/getFileName",index.getFileName); **//this is the script to get the file name, it is from index.js**
var server=app.listen(3000,function(){
console.log("Express is running on port 3000");
});
index.js // this is the js file for getting file name
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
getFileName=function (req,res){
global.filename=req.body.filename; **//this is the global variable which stores the file name**
res.send('true');
};
module.exports = {router:router,getFileName:getFileName};
vis.js // this is the file used to connect with Rserve and pass the name to R code
var rio = require("rio");
var arg={};
exports.rio = function(req, res){
arg={names:[global.filename]};
console.log(arg);
options = {
entryPoint:"nameoffile",
data: arg,
host : "127.0.0.1",
port : 6311,
callback: function (err, val) {
if (!err) {
console.log("RETURN:"+val);
return res.send({'success':true,'res':val});
} else {
console.log("ERROR:Rserve call failed")
return res.send({'success':false});
}
},
}
rio.enableDebug(true);
rio.sourceAndEval(__dirname + "/Rcode/test.R",options);
};
It looks like you aren't calling out to /vis/rio at any point when you make the call out to your server.
You'll either need to make a second call on the client side to /vis/rio or if you want to use that section, you can import/require the module in index.js and include it in getFileName and just call out to the function there before you return the file. I'm not super familiar with rio, but I don't see any access point in your code to that function.
Edit: If I understand what you're trying to do correctly, you can always make a second request (to /vis/rio) in the success callback of your first ajax call.

Express.js and form validation

I'm tring to create a simple node- with express.js script that will sum 3 numbers.
On index I have this:
index.jade
!!! 5
html
head
title Test
body
form(name='form1', method='post', action='/')
label(for='1')
input#1(type='text', name='1')
label(for='2')
input#2(type='text', name='2')
label(for='3')
input#3(type='text', name='3')
input(name='submit', type='button', value='submit')
#result
and also i'm now writing the serverside - app.js with req and res object but how to return a result... also result = 1id + 2id + 3id
app.js
var express = require('express');
app = express.createServer();
app.use(express.bodyParser());
app.post('/', function(req, res){
var i = req.param('1', null);
var j = req.param('2', null);
var k = req.param('3', null);
var r = i+j+k;
res.send(r);
});
How I to send results (r) into div id Result on index.jade... so how to return result to index.jade
also here is pastebin code: http://pastebin.com/J9MRFCaE ... i'm new to node and express and sorry for stupid question...
It's simple, just call your "index.jade" rendering passing your data (instead of 'res.send(r);') :
res.render('index', {
result: r
});
And display "result" variable in your jade file :
#result #{result}
Additional information on jade code and express rendering

Categories