I send an html file to client with res.write() method. I also want to send an object attached to this html.
I tried to stringify that object and write it like I wrote the html file, but when I do that, my stringified json object remains outside of the html. I need that json object to be inside of the html, so I can parse it with the client side js file.
how should I fix that?
I tried to send it as a Json object. but I couldnt get it through the html.
app.get('/uniform', (req,res) => {
fs.readFile('uniformflowindex.html', function(err, data) {
var channelobj = JSON.stringify(channel);
res.write(data);
res.write("<div id='objectstring'>" + channelobj + "</div>");
res.end('');
});
});
it gives the output:
<html>
...
my html file
...
</html>
<div id='objectstring'>{"_events":{},"_eventsCount":0,"Discharge":20,"FlowDepth":5.......}</div>
I just want this div to be in html file..
You could have a wildcard in your html code and then replace the wildcard with your div content.
For example:
<html>
...
my html file
...
[[wildcard]]
</html>
and then use:
app.get('/uniform', (req,res) => {
fs.readFile('uniformflowindex.html', function(err, data) {
var channelobj = JSON.stringify(channel);
res.write(data.replace('[[wildcard]]', "<div id='objectstring'>" + channelobj + "</div>"));
res.end();
})
});
Alternatively may not add a wildcard in your html and just replace one of your closing tags such as <\body> or <\html> with your content + the closing tag itself...
app.get('/uniform', (req,res) => {
fs.readFile('uniformflowindex.html', function(err, data) {
var channelobj = JSON.stringify(channel);
res.write(data.replace('</body>', "<div id='objectstring'>" + channelobj + "</div></body>"));
res.end();
})
});
HTML file:
<html>
...
{ content }
...
</html>
your code:
app.get('/uniform', (req,res) => {
fs.readFile('uniformflowindex.html', function(err, data) {
var channelobj = JSON.stringify(channel);
data = data.replace('{ content }', "<div id='objectstring'>" + channelobj + "</div>");
res.end(data);
})
});
Related
I'm have trouble accessing json data within the console. If for instance I wanted to type in courses[0].name or courses.length, I get the error "courses is not defined". I'm definitely missing something here but I'm unsure how to go about it. The list is generating just fine on the DOM, but I want want to access specific parts within the array.
$(document).ready(function () {
var showData = $('#show-data');
$.getJSON('../undergraduate/ug.json', function (data) {
console.log(data);
var courses = data.courses.map(function (course) {
return course.code + ': ' + course.name;
});
if (courses.length) {
var content = '<li>' + courses.join('</li><li>') + '</li>';
var list = $('<ul />').html(content);
showData.append(list);
}
});
});
<body>
Get JSON data
<div id="show-data"></div>
</body>
The json data also seems to be appearing fine initially on load within the console log:
Any help would be very appreciated. Thanks in advance!
In html, i am passing the value to the node js file in post form using the form tag.
I created a new value on the server side with the value passed in html.
I want to insert the value back into the textbox(result) on the html.
And I want this process to happen on the same page.
I am writing html with the pug template engine and router name is form.
form(action='form' method='post')
p.lead
textarea(style='resize:none; width:400px; height:300px;' name='description' onkeydown="if(event.keyCode===9){var v=this.value,s=this.selectionStart,e=this.selectionEnd;this.value=v.substring(0, s)+'\t'+v.substring(e);this.selectionStart=this.selectionEnd=s+1;return false;}") #include<stdio.h>
int main()
{
return 0;
}
p
input(type='text' style='resize:none; width:400px; height:50px;' name='result' readonly='readonly')
p
input(type='submit' value='submit' class='btn btn-success')
The html file is created in this way and is sending these values to the server using the post method.
app.post('/form',function(req,res) {
var description = req.body.description;
var source = description.split(/\r\n|\r\n/).join("\n");
fs.writeFile(file,source,'utf8',function(error) {
console.log('write end');
});
var compile = spawn('gcc',[file]);
compile.stdout.on('data',function(data) {
console.log('stdout: '+data);
});
compile.stderr.on('data',function(data){
console.log(String(data));
});
compile.on('close',function(data){
if(data ==0) {
var run = spawn('./a.out',[]);
run.stdout.on('data',function(output){
console.log('end');
});
run.stderr.on('data', function (output) {
console.log(String(output));
});
run.on('close', function (output) {
console.log('stdout: ' + output);
});
models.Code.create( {
title: 'test1',
code: source
})
.catch(err => {
console.error(err);
});
}
});
});
It is an excerpt from the post part of the code.
I have succeeded in compiling the value written in html textarea on the server side and extracting the result.
But I do not know how to send the value back to html.
You can use express js middleware to pass a data from node.js server tk all views
Like this
app.use(function(req,res,next){
res.locals.yourvariable = req.yourvariable;
next();
});
Hope it will be helpfull
I need to give var into my html like server -> client
I'm not good at english and this situation is hard to explain so i will show you the code
html (index.html):
<script type="text/javascript">
console.log(tmp) //lol!
</script>
node.js:
fs.readFile('./index.html', (err, html) => {
if (err) {
response.statusCode = 404;
response.end(`error!`);
}
else
{
tmp="lol!"
response.write(html);
response.end();
}
});
server should response and give value to client same time. but it didn't work.
i don't want use external modules like express.js or ajax anything need to download things as it's possible
could you help me?
fs.readFile('./index.html', (err, html) => {
if (err) {
}
else
{
var tmp = new Object();
tmp.string = "hello world!"
var go = JSON.stringify(tmp)
res.write(`<div id="data"><div id="list" data-list='${go}'></div></div>`);
res.write(html);
res.end();
}
});
HTML:
var data = JSON.parse(document.getElementById("list").getAttribute("data-list"));
alert(data.string);
make a div element and set attribute, then write in response.
I am using a javascript Get call to grab the json data for a collection I created in deployd. I got this code directly from the deployd backend. It gives me a json array that is put into the console, but I am far from figuring out how to parse the json not sure if thats the right term, and output it into seperate p tags for each item within in the collection.
I also have included jQuery and I am assuming based on what I have looked into online that it makes it much easier to do so. Also if there is a better library than jQuery to learn to do this with, or something that makes more sense for deployd lets say Angular, I would love to be steered in the right direction.
Here is the javascript get request provided.
dpd.things.get(function (result, err) {
if(err) return console.log(err);
console.log(result);
});
I have tried looking at a example app off the deployd site to see how they did it but havent quite figured it out here is my failed attempt below
<body>
<h1>Welcome to Deployd!</h1>
<p>You've just created a Deployd app. You can add front-end files in the <code>public</code> folder.</p>
<p>If you're new to Deployd, have a look at the Getting Started Guide or <a href="http://docs.deployd.com/docs/getting-started/your-first-api.md">Hello World Tutorial<a>.</p>
<p class="hide" id="empty">You don't have any todos! Add one now:</p>
<ul id="todos" class="unstyled"></ul>
</body>
<script>
function getTodos() {
// Get all todos
dpd.things.get(function(result, err) {
if (err) {
// Alert if there's an error
return alert(err.message || "an error occurred");
}
if (!result.length) {
$('#empty').show();
}
// todos is an array
result.forEach(function(thingy) {
renderTodo(thingy);
});
});
}
function renderTodo(thingy) {
var $el = $('<li>');
// $label = $('<label class="checkbox">')});
$el.appendTo('#todos');
$('#empty').hide();
}
</script>
NEW RECCOMENDED CODE NOT WORKING
function getTodos() {
// Get all todos
dpd.things.get(function(result, err) {
if (err) {
// Alert if there's an error
return alert(err.message || "an error occurred");
}
if (!result.length) {
$('#empty').show();
}
// todos is an array
result.forEach(function(thingy) {
renderTodo(thingy);
});
});
}
function renderTodo(thingy) {
var $el = $('<li>');
$el.text(thingy);
$el.appendTo('#todos');
$('#empty').hide();
}
Here is the site running on localtunnel so you can see the console. https://twig.localtunnel.me
Try adding 'thingy' in the code so it will display the items returned from the collection; Just make sure a collection is being returned.
If thingy is plain text:
var $el = $('<li>')
$el.text(thingy);
If thingy includes html with text:
var $el = $('<li>')
$el.html(thingy);
I ended up doing this in the end based off of this stack overflow answer
dpd.things.get(function(result, error) {
console.log(result);
$.each(result, function(i,result){
content = '<p id=" ' + result.name + ' ">'
+ result.name + '</p>' + '<p>' + result.about +
'</p>' + '<p>' + result.id + '</p>'
$(content).appendTo("#test");
});
});
I want to unzip a file that contains an html page, css, and js directories. I want to unzip this temporarily and view the html in an iFrame, preferrably. I am using jszip which is working. I got the html to load, but how do I add the image, js, and css folders into the iFrame?
Here is what I have so far...
<div id="jszip_utils"></div>
<iframe id="iframe"></iframe>
<script type="text/javascript">
function showError(elt, err) {
elt.innerHTML = "<p class='alert alert-danger'>" + err + "</p>";
}
function showContent(elt, content) {
elt.innerHTML = "<p class='alert alert-success'>loaded !<br/>" +
"Content = " + content + "</p>";
}
var htmltext = JSZipUtils.getBinaryContent("/zip/myWebsite.zip", function (err, data) {
var elt = document.getElementById('jszip_utils');
if (err) {
showError(elt, err);
return;
}
try {
JSZip.loadAsync(data)
.then(function (zip) {
for(var name in zip.files) {
if (name.substring(name.lastIndexOf('.') + 1) === "html") {
return zip.file(name).async("string");
}
}
return zip.file("").async("string");
})
.then(function success(text) {
$('#iframe').contents().find('html').html(text);
showContent(elt, text);
}, function error(e) {
showError(elt, e);
});
} catch(e) {
showError(elt, e);
}
});
</script>
This gets the html, but the js css and image files are not showing up. I believe I need to do some sort of fake routing, but I'm not sure how I would be able to do that. Thanks for your help.
If the html/js in the zip is not too complicated, for instance an AngularJS app that has routes for partials, this is possible.
The trick is to replace css,js,img src/href urls that point to a file in the zip with either:
Object Url: URL.createObjectURL(Blob or File object);
Data Url: data:[<mediatype>][;base64],<data>
Or in the case of js and css inject the content directly into the appropriate element
After replacing the src/href references than just inject the new html into the iframe.
Step 1: Parse the html so you can manipulate it
//html from a call like zip.file("index.html").async("string")
let parser = new DOMParser;
let doc = parser.parseFromString(html,"text/html");
Step 2: Find all elements with a relative path (e.g. /imgs/img.jpg) as they are easier to deal with as you can then use that path for zip.file
//Simply finds all resource elements, then filters all that dont start with '/'
var elements = jQuery("link[href],script[src],img[src]",doc).filter(function(){
return /^\//.test(this.href || this.src);
});
Step 3: Replace src,href with object url, data url, or direct content
//assume element is the html element: <script src="/js/main.js"></script>
zip.file(element.src).async("string").then(jsText=>{
element.src = "data:text/javascript,"+encodeURIComponent(jsText);
});
Step 4: Get the new html text and inject it into the iframe
let newHTML = doc.documentElement.outerHTML;
var viewer = document.querySelector('#iframeID');
viewer = viewer.contentWindow || viewer.contentDocument.document || viewer.contentDocument;
viewer.document.open();
viewer.document.write(html);
viewer.document.close();
JSFiddle Demo - Demonstrates replacing the src/href urls
As a security note, if you are using zip files that you do not know the contents of, you should run the whole app in a protected iframe