How to Display Real Time variables node.js with express - javascript

So , I have been try to display my variables "pares", "impares" ,"ninguno" in real time as the image below I used app.get and inside that a response.write to print de varibles, but the problem is if I want the varaibles to update, I need to reload the page everytime, is there anyway to print them in real time?,enter image description here
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var reload = require('reload');
var http = require('http');
var server = http.createServer(app);
var impares = 0;
var pares = 0;
var ninguno =0;
app.use(bodyParser.urlencoded({extended : true}));
app.use(bodyParser.json());
app.post('/arduino', function(request, response) {
console.log("Arduino asking data");
var stringInform = (Object.keys(request.body)).toString();
var stringA = stringInform.split("|");
var dato1= parseInt(stringA[0],10);
var dato2 = parseInt(stringA[1],10);
response.send('Hello Arduino');
Parimpar(dato1,dato2);
response.end();
console.log(dato1);
console.log(dato2);
console.log(ninguno);
});
app.get('/arduino', function(request, response) {
response.write('PARES:'+ pares + ' '+ 'IMPARES:' + impares + ' ' + 'NINGUNO:'+ ninguno);
response.end();
});
app.listen(8080);
function Parimpar(c,i)
{
if (c%2 == 0 && i%2 == 0)
{
pares = pares +1;
// return pares;
}
else if (c%2 != 0 && i%2 != 0)
{
impares = impares + 1;
//return impares;
}
else
{
ninguno = ninguno +1 ;
//return ninguno;
}
}

You Can Use Web-sockets To Emit Events When The Values Are Updated . The Easier Way Is to Setup A socket.io webserver and emit values to all the connected values.
Check Out https://socket.io/

Related

JQuery ajax call returns 404 page not found

I am trying to parse a JSON string upon loading the page but I get the following error in the web dev tools: GET http://ipaddress/CulturalEvents/calWrapper 404 not found (Note: ipaddress is the address for our IIS web server). When I click on the error I get the following error: Failed to load resource: the server responded with a status of 404 not found.
Here is my index.js
var titles = new Array();
var descriptions = new Array();
var count = 0;
// Function to cycle through events on display
function changeText() {
$('#evtName').html(titles[count]);
$('#evtDesc').html(descriptions[count]);
if (count < titles.length - 1) {
count++;
} else {
count = 0;
}
}
$(document).ready(function () {
$.ajax({
url:'/CulturalEvents/calWrapper',
type: 'GET',
dataType: 'json',
success: function(calJSON){
let eventCheck = 0;
var today = new Date();
var yyyy = today.getFullYear();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0');
today = yyyy + mm + dd;
console.log(today);
for (let i = 0; i < calJSON.length; i++){
if (calJSON[i].startDT == today){
eventCheck = 1;
} else {
eventCheck = 0;
}
if (eventCheck == 1){
titles.push(calJSON[i].summary);
if (calJSON[i].description == ""){
descriptions.push("No description.");
} else{
descriptions.push(calJSON[i].description)
}
} else {
titles.push("No events today.");
descriptions.push("If you know of an event that is not displayed feel free to contact the Diversity Equity and Inclusion committee.")
}
}
}
});
// Rotate through events
changeText();
setInterval(changeText, 10000);
});
It can't find my ajax url '/CulturalEvents/calWrapper'. Note I can run this locally and look for the endpoint /calWrapper and it works perfectly fine, but when I run it on the IIS server it stops working.
Here is my app.js as well:
// C library API
const ffi = require('ffi');
// Express app
const express = require('express');
const app = express();
const path = require('path')
const port = process.env.PORT
const fs = require('fs');
app.use(express.static('public'));
// Send HTML
app.get('/CulturalEvents/', function(req, res){
res.sendFile(path.join(__dirname + '/public/index.html'));
});
// Send style
app.get('/CulturalEvents/style.css', function(req, res) {
res.sendFile(path.join(__dirname + '/public/style.css'));
});
// send JavaScript
app.get('/CulturalEvents/index.js', function (req, res) {
res.readFile(path.join(__dirname + '/public/index.js'), 'utf8', function(err, contents){
res.send(contents);
});
});
// Wrapper function for c library
let wrapper = ffi.Library('./bin/libcalWrapper', {
'calWrapper': [ 'string', [ 'string' ] ]
});
app.get('/CulturalEvents/calWrapper', function (req, res) {
var tempStr = JSON.parse(wrapper.calWrapper(__dirname + "/multiculturalcalendar2021.ics"));
res.send(tempStr);
});
app.listen(port, () => {
console.log(__dirname + '/public/index.js');
});
Also the directory structure is as follows:
CulturalEvents/
public/
index.js
index.html
style.css
app.js
package.json
web.confi

ReferenceError: window is not defined when using mergeImages in express.js

I'm using mergeImages on my express.js server but I'm getting error of "ReferenceError: window is not defined". I don't know what it's saying. Even I haven't used window word in my code.
Please check my code of server.js. at the end of the code I have mergeimage function.
const express = require('express');
const app = express();
const fs = require('fs');
const mergeImages = require('merge-images');
const bodyParser = require('body-parser');
const multer = require('multer');
const { response } = require('express');
const cors = require('cors');
app.use(cors());
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.get('/', (req,res) => {
res.send('this is express!');
})
app.listen(8000, (err) =>{
if(err) console.log(err);
console.log('Server Started please listen to port: 8000');
})
app.get('/get-image', function(req,res,next){
const pixel_base_value = 1.31;
const top_margin = 5;
const left_margin = 3;
var photo_frame = [];
for(var j = 1; j <= req.query.row; j++){
var total_width_check = 0;
var total_height_check = 0;
for(var k= 1; k <= req.query.col; k++){
var height_cal = req.query.photo_height*pixel_base_value;
var width_cal = req.query.photo_width*pixel_base_value;
if(j !== 1){
var top1 = top_margin + height_cal + 3;
}else{
top1 = top_margin;
}
if(k !== 1){
var left1 = (width_cal * (k-1) + (left_margin * k));
}else{
left1 = left_margin;
}
total_width_check = total_width_check + req.query.photo_width*pixel_base_value + left_margin;
total_height_check = total_height_check + req.query.photo_height*pixel_base_value + top_margin;
if(total_width_check >= req.query.board_width*pixel_base_value-3 && total_height_check >= req.query.board_height*pixel_base_value-3){
}else{
photo_frame.push({src:'http://localhost:8000/image/'+ req.query.img_name +'', x: left1, y: top1, width: width_cal, height: height_cal});
}
}
total_width_check = 0;
}
//check photo_frame is a valid Array
mergeImages(photo_frame).then((b64) =>{ //add options here for canvas
console.log(b64)
},(error) =>{
console.log(error);
} );
return res.end('done');
})
Please help!
Thanks!
I think for node usage, you should add node-canvas and pass it via option object. Currently, you are not using the canvas.
const mergeImages = require('merge-images');
const { Canvas, Image } = require('canvas'); // import this
mergeImages(['./body.png', './eyes.png', './mouth.png'], {. //pass Valid images in array
Canvas: Canvas, // here you need to add canvas
Image: Image
})
.then(b64 => ...);
For sample project in Node.js, you can check here

JavaScript for loop for object

I'm using Express to 'capture' data. I'm using a put request. My request is
localhost:3000/units/10 , with the body being:
{
"relayon0" : 400,
"relayoff0" : 400
}
And my code is:
var bodyParser = require('body-parser');
var mysql = require('mysql');
var express = require('express');
var app = express();
var conn = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'plc'
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.put('/units/:id', function(req,res){
var id = req.params.id;
var relayon = [];
var relayoff = [];
for(var i = 0; i < 8; i++){
relayon[i] = JSON.stringify(req.body.relayon + i);
relay[i] = JSON.stringify(req.body.relayoff + i);
}
res.send(relayon[0]);
});
app.listen(3000);
The response returns null.
Any ideas on what the issue is?
What you probably want is req.body['relayon' + i] and req.body['relayoff' + i].
Requesting req.body.relayon + i results in value of req.body.relayon (which is undefined) being added with number, which results with NaN. Being stringified, it results with "null".

Write data to JSON file

I'm trying to write a list of habit objects to a JSON file, but I can't figure it out. I'm doing this because I want to use this JSON file with node.js.
I've created a section with a class called "habits" that I want to fill this JSON file with, the section itself gets the habit objects from this piece of code:
var addHabit = function () {
var $new_habit = {
"name":"",
"value":0,
"goal":0,
"html": null
}
if ($(".habit-input input").val() !== "") {
$new_habit.name = $("#habitinput .name").val();
$new_habit.value = $("#habitinput .value").val();
$new_habit.goal = $("#habitinput .goal").val();
$new_habit.html = $("<p id="+uid+">").html("<span class=\"name\">"+$new_habit.name+"</span> <span class=\"val\">" + $new_habit.value + "</span>/" + "<span class=\"goal\">"+$new_habit.goal + "</span>"+
"<button class=\"plus\">+</button><button class=\"min\">-</button><button class=\"delete\">x</button><button class=\"mod\">modify</button>");
console.log($new_habit);
$(".habits").append($new_habit.html);
$(".habit-input input").val("");
$("#"+uid + " .plus").on("click", function (event) {
var val = parseInt( $(this).parent().find(".val").text());
$(this).parent().find(".val").text( val+1 );
event.preventDefault();
});
$("#"+uid + " .min").on("click", function (event) {
var val = parseInt( $(this).parent().find(".val").text());
$(this).parent().find(".val").text( val-1 );
event.preventDefault();
});
$("#"+uid + " .delete").on("click", function (event) {
$(this).parent().remove();
event.preventDefault();
});
$("#"+uid + " .mod").on("click", function (event) {
var val = parseInt( $(this).parent().find(".val").text());
var name = parseInt( $(this).parent().find(".name").text());
var goal = parseInt( $(this).parent().find(".goal").text());
$(this).parent().find(".val").text(val = $("#habitinput .value").val());
$(this).parent().find(".name").text(name = $("#habitinput .name").val());
$(this).parent().find(".goal").text(goal = $("#habitinput .goal").val());
event.preventDefault();
});
uid++;
};
};
I want to read the section "habits" into the JSON file so I can use it in this node.js file:
var express = require("express");
var url = require("url");
var http = require("http");
var fs = require('fs');
var port = 3000;
var app = express();
app.use(express.static(__dirname + "/client"));
//logger component
app.use(function (req, res, next) {
console.log("[LOG] %s %s", new Date(), req.url);
next();
});
http.createServer(app).listen(port);
//clients requests habits
app.get("/habits", function (req, res) {
console.log("Habits requested!");
res.sendfile('Habit/client/habits.json');
});
What I hope to achieve is that when I go to localhost:3000/habits in my browser that I get all the habit objects in JSON format.
At the moment when I go to localhost:3000/habits I get this {"type":"Buffer","data":[123,13,10,32,32,32,32,34,121,101,121,34,32,58,32,49,50,13,10,125]}
Any help would be greatly appreciated
You're getting a buffer back from the GET/habits. Need to convert it to a something you can read
try calling toString('utf-8')
OR
import bodyParser from 'body-parser';
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

Trouble emitting information on clientside with socket.io

I am using express.js, mongoose, jquery and socket.io
I am trying to pass the object "allFightScores" to the socket on clientside. Here is where I am requesting information from mongoose in my routes/index.js:
var models = require('../models/index.js');
var passport = require('passport');
var crawl = require('../crawler.js');
var flash = require('connect-flash');
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
exports.submit_scores = function(req, res){
var scored_fight = new models.UserScore({
"f1": req.body.f1,
"f2": req.body.f2,
"f1_roundScores": req.body.f1_roundScores,
"f2_roundScores": req.body.f2_roundScores,
"f1_score": req.body.f1_score,
"f2_score": req.body.f2_score,
"user_email": req.body.user_email
});
models.UserScore.find({
"f1": scored_fight.f1,
"f2": scored_fight.f2,
"f1_score": scored_fight.f1_score,
"f2_score": scored_fight.f2_score,
"user_email": scored_fight.user_email
}, function(err, data){
if (data.length === 0){
scored_fight.save(function(err, user_fight){
if (err) {
return "error";
}
else {
models.UserScore.find({"f1": user_fight.f1, "f2": user_fight.f2}, function(err, allFightScores){
console.log("from index-routes " +allFightScores);
io.sockets.emit('show scores', allFightScores)
})
}
})
//put a callback on the user_scored_fight data, also emit that data with the average scores;
res.json(scored_fight);
}
else if (data[0].f1 === scored_fight.f1 && data[0].f2 === scored_fight.f2 && data[0].user_email === scored_fight.user_email) {
res.json(200);
console.log("data already judged.");
}
})
}
Here is where I am catching the data on my clientside (public/javascripts/script.js):
jQuery(function($){
socket = io.connect();
var $group_f1_score = $('#gf1_score');
var $group_f2_score = $('#gf2_score');
socket.on('show scores', function(mongooseData){
console.log("mongooseData from scripts " + mongooseData)
$group_f1_score.empty();
$group_f2_score.empty();
//sum fighter scores for all user submissions
var f1_sumScore = 0;
var f2_sumScore = 0;
for (var i = 0; i < mongooseData.length; i++){
f1_sumScore += mongooseData[i].f1_score;
f2_sumScore += mongooseData[i].f2_score;
}
//get the simple average
var f1_avgScore = f1_sumScore/mongooseData.length;
var f2_avgScore = f2_sumScore/mongooseData.length;
$group_f1_score.append(f1_avgScore);
$group_f2_score.append(f2_avgScore);
})
})
I am not sure why the data is not emitting to my clientside and am out of ideas. Am I querying the data and passing it in the callback correctly?
I can't see this in your code:
server.listen(port);

Categories