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
Related
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
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/
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 }));
Hi I'm making a chat with node js and I have a question. The chat is global, without rooms but users can only see and write to users in their buddy list. So when they connect to the server, they'll send also the user id and the buddy list as array. In the server I have a global variable with online users. Now, which is the best way to emit the event to users in the buddy list?
This is my current code:
var express = require('express');
var cors = require('cors');
var crypto = require('crypto');
var app = express();
var port = process.env.PORT;
var mongoose = require('mongoose');
var jwt = require('jsonwebtoken');
var socketio = require('socket.io');
var confdb = require('./lib/config-db.js');
var conf = require('./lib/config.js');
var db = require('./lib/chat-db');
var whitelist = [];
var secret_st = '';
var chrlimit = '';
var socketio_jwt = require('socketio-jwt');
var uidlist = {};
var id = {};
var mongodburl = process.env.MONGODB_URI;
// initialize db ===============================================================
mongoose.connect(mongodburl); // connect to our database
mongoose.Promise = global.Promise;
// set up our express application
confdb.findOne({'check': '1'}).exec(function(err, docs){
if (docs) {
whitelist = docs.origin;
secret_st = docs.spku;
chrlimit = docs.chrlimit;
if (docs.badwld) {
badwl = JSON.parse(docs.badwld);
}
} else {
conf.saveconfig();
}
startall();
});
function startall() {
var corsOptions = {
origin: function(origin, callback){
var originIsWhitelisted = whitelist.indexOf(origin) !== -1;
callback(null, originIsWhitelisted);
}
};
app.use(cors(corsOptions), function(req, res, next) {
next();
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// launch ======================================================================
var server = app.listen(port);
var io = socketio.listen(server);
//Routes ======================================================
app.get('/', function(req, res) {
res.writeHead(200);
res.end();
});
var nspm = io.of('/member');
nspm.use(socketio_jwt.authorize({
secret: secret_st,
handshake: true
}));
nspm.on('connection', function(socket) {
db.c_oneusr(socket.decoded_token, function(err, docs){
nspm.to(socket.id).emit('ckusr', 'ok');
initializeConnection(socket, 0);
});
});
function initializeConnection(socket, lstshout){
showActiveUsers(socket, lstshout);
}
function showActiveUsers(socket, lstshout){
socket.uid = socket.decoded_token.uid;
uidlist[socket.uid] = 1;
if (!id[socket.uid]) {
id[socket.uid] = {};
}
if (!msgtime[socket.uid]) {
msgtime[socket.uid] = [];
}
msgtime[socket.uid]['lpmsgt'] = lstshout;
id[socket.uid][socket.id] = 1;
socket.emit('login', {
uidlist: uidlist
});
// I need to change this and emit it only to buddies
socket.broadcast.emit('user joined', {
uidlist: uidlist,
uid: socket.uid
});
data = [];
data["uid"] = socket.decoded_token.uid;
data["id"] = socket.id;
data["buddies"] = socket.decoded_token.buddies;
db.updpml(data);
}
}
I'm trying to store emails from sendgrid via the inbound webhook using node, express and multer. There is an example on sendgrids site as below:
var express = require('express');
var multer = require('multer');
var upload = multer();
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.use(multer());
});
app.post('/parse', upload.array('files', 3) function (req, res) {
var from = req.body.from;
var text = req.body.text;
var subject = req.body.subject;
var num_attachments = req.body.attachments;
for (i = 1; i <= num_attachments; i++){
var attachment = req.files['attachment' + i];
// attachment will be a File object
}
});
var server = app.listen(app.get('port'), function() {
console.log('Listening on port %d', server.address().port);
});
This code throws an error when an email with an attachment is sent. The error is "unexpected field". I assume that the declaration for array.upload("files",3) is where the issue lies. Has anybody solved this?
You can solve this by using .any() when you don't the field name (see documentation for any()
Here's an example code
app.post('/parse', upload.any() function (req, res) {
var from = req.body.from;
var text = req.body.text;
var subject = req.body.subject;
var num_attachments = req.body.attachments;
for (i = 1; i <= num_attachments; i++){
var attachment = req.files['attachment' + i];
// attachment will be a File object
}
});