Chart.js with Node.js - node.js

Assume that I want to make a bar chart in HTML. I use node.js as a backend and get data from the database through node.js. I usually will render the data to view into ejs files. Is it possible for me to use database data from node.js then pass it to javascript (client-side) where I am creating the chart.js?

Try this: replace result with your data!
const fs = require('fs');
var express = require('express');
var app = express();
var path = require('path');
var Chart = require('chart.js');
var result =[3,6,9];
app.get('/', function(req, res){
let _resLine = '<h1>Ereignisse: ' + result+'</h1>';
console.log('show chart:');
console.log(_resLine);
_html = "<script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js'></script>"+
"<canvas id='bar-chart' width='800' height='450'></canvas>"+
"<script>"+
"var logChart = new Chart(document.getElementById('bar-chart'), {"+
"type: 'horizontalBar',"+
"data: {"+
"labels: ['Ereignis1', 'Ereignis2', 'Ereignis3'],"+
"datasets: ["+
"{"+
"label: 'Aufrufe',"+
"backgroundColor: ['#3e95cd', '#8e5ea2','#3cba9f'],"+
"data: ["+result[0]+","+result[1]+","+result[2]+"]"+
"}"+
"]"+
"},"+
"options: {"+
"legend: { display: false },"+
"title: {"+
"display: true,"+
"text: 'Ereignisse '"+
"}"+
"}"+
"});"+
"</script>";
res.send(_html);
});
app.listen(3005);
cmd: node showChart.js
URLs:
http://localhost:3005
See also example in my git archive

Related

problem with reading path uploading a file in nodejs

I started some time ago a project with angular and nodejs with mongodb. but I updated nodejs at latest version.
when I upload a file a image the file is inserted into the backend but I can not get the full path of the file. (I tested with postman).
TypeError: Cannot read properties of undefined (reading 'path') at uploadAvatar (/var/www/html/room/room-backend/controllers/room.js:749:36)
the line 749 is var file = req.files.file0.path;
I using in the controller room.js
var fs = require('fs');
var path = require('path');
but maybe nodejs 18 is using other logic to work with path and files.
I am triying to figure out in the documentation the issue. but without results.
roomsjs routes
'use strict'
var express = require('express');
var RoomController = require('../controllers/room');
var router = express.Router();
var md_auth = require('../middlewares/authenticated');
var multipart = require('connect-multiparty');
var md_upload = multipart({ uploadDir: './uploads/rooms' });
// Rutas de usuarios
router.post('/save', RoomController.save);
router.put('/update', md_auth.authenticated, RoomController.update);
router.put('/updateimage1', RoomController.updateImage1);
router.post('/saveimg', RoomController.saveImg);
//router.post('/saveimg/:id/:image1/', RoomController.saveImg);
router.post('/upload-avatar', md_upload, RoomController.uploadAvatar);
// //router.post('/upload-avatar', [md_auth.authenticated, md_upload], AdminController.uploadAvatar);
router.get('/avatar/:fileName', RoomController.avatar);
//router.get('/avatar2/:image2', RoomController.avatar2);
// router.delete('/book/:id', md_auth.authenticated, AdminController.delete);
router.delete('/delete-avatar/:fileName', RoomController.deleteAvatar);
router.get('/rooms/:page', RoomController.getRooms);
router.get('/roomsEs/:page', RoomController.getRoomsEs);
router.get('/roomsfull/:page', RoomController.getRoomsFull);
// //router.get('/books/', AdminController.getBooks);
router.get('/room/:roomId', RoomController.getRoom);
router.delete('/delete/:roomid', md_auth.authenticated, RoomController.delete);
// router.get('/search/:search', AdminController.search);

Get Query Params in express node js

The url contains all the query strings after the # key
http://localhost:3002/callback#access_token=nQevH_hZSjs3qdOoLNnAIITwqd3lCdkq&expires_in=7200&token_type=Bearer
how do we access the params after #
var url = 'http://localhost:3002/callback#access_token=nQevH_hZSjs3qdOoLNnAIITwqd3lCdkq&expires_in=7200&token_type=Bearer';
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\#&]' + name + '=([^&#]*)');
var results = regex.exec(url);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
console.log(getUrlParameter('access_token'));
console.log(getUrlParameter('expires_in'));
console.log(getUrlParameter('token_type'));
Best practice is to use ? instead of #
So your url should be
http://localhost:3002/callback?access_token=nQevH_hZSjs3qdOoLNnAIITwqd3lCdkq&expires_in=7200&token_type=Bearer
Now you can get the query params with below method
var express = require('express');
var app = express();
app.get('/callback', function(req, res){
console.log('access_token: ' + req.query.access_token);
console.log('expires_in: ' + req.query.expires_in);
console.log('token_type: ' + req.query. token_type);
});
app.listen(3000);
Anything after the # isn't sent to the server by the browser.. you can
only parse it if the url is generated or obtained from the server. Then you can use nodes in-built url module to parse symbols in the url
You can use the substring() method:
EDIT: the string you can get from response.body. You have to use body-parser or express.json
let str = "http://localhost:3002/callback#access_token=nQevH_hZSjs3qdOoLNnAIITwqd3lCdkq&expires_in=7200&token_type=Bearer";
let index=str.indexOf("#");
let res = str.substring(index+1);
Output:
$ node server.js
access_token=nQevH_hZSjs3qdOoLNnAIITwqd3lCdkq&expires_in=7200&token_type=Bearer

Nodejs memory usage

I think I have a problem with memory usage. I have a node.js server :
var arcadeGames = require('./server/js/arcade');
var cardsGames = require('./server/js/cards');
requires modules that exports object required from .json data
var http = require('http');
var express = require('express');
var app = express();
var server = http.createServer(app);
//var io = require('socket.io').listen(server);
//var fs = require('fs');
app.get('/specificCategory/:id',function(req,res,next){
switch(req.params.id){
case "Cards":
console.log(cardsGames.titles);
break;
case "Action":
console.log(actionGames.titles);
break;
default:
console.log("undefined");
}
//var specificCaategory = require('./server/js/'+ req.params.id.toLowerCase());
//var categoryTitlesAndUrlThumbs = spe
//console.log(specificCaategory.titles);
})
(both way are working the same commented one or the one with switch)
the get function is called from browser by clicking the categories ex :Cards, Action and send the request through http, controller from angularjs. The problem is that when I console.loged out on server first click on each category works fine, but after that, the server takes a lot of time to console.log out the info.(what will happends in browser if this is so hard for server).
Have I done something to load the memory so much?
Add res.end(); after your switch case.

custom module not defined in nodejs express app

we made a custom module for express app but getting this error somename is not defined
here is our code
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var somename = require('./somename/common');
// console.log(wahapar.ucfirst("d"));
var routes = require('./routes/index');
var users = require('./routes/users');
common.js
module.exports = {
ucfirst: function(str){
// discuss at: http://phpjs.org/functions/ucfirst/
// original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// bugfixed by: Onno Marsman
// improved by: Brett Zamir (http://brett-zamir.me)
// example 1: ucfirst('kevin van zonneveld');
// returns 1: 'Kevin van zonneveld'
str += '';
var f = str.charAt(0).toUpperCase();
return f + str.substr(1);
},
};
ejs view
<%= somename.ucfirst("this is a string") %>
while console.log(somename.ucfirst("d")); is showing output in the terminal
You should pass your module as a local variable into express app.
app.locals.somename = require('./somename/common');
Then you will be able to use inside ejs templates.
From the express docs app.locals
The app.locals object is a JavaScript object, and its properties are
local variables within the application.
Once set, the value of app.locals properties persist throughout the
life of the application, in contrast with res.locals properties that
are valid only for the lifetime of the request.
You can access local variables in templates rendered within the
application. This is useful for providing helper functions to
templates, as well as app-level data. Locals are available in
middleware via req.app.locals

java.lang.NoClassDefFoundError at runtime when using express framework and node.js

I am trying to write a sample code to create an instance of a java class and then invoke a method using that instance. I am using node-java module to do this. The code compiles without any error. However when I hit the URL which actually hits the same code then I get the class not found exception.
I have verified that the jar and it is there in the same directory as index.js and the jar also contains the class file (Application.class) for which the instance is being created.
My index.js file
var java = require("java");
java.classpath.push("demo.jar");
var express = require('express');
var router = express.Router();
var Application = java.import('Application');
/* GET home page. */
router.get('/', function(req, res) {
var application = new Application();
var resp = application.getResponse();
res.render('index', { title: resp });
});
module.exports = router;
Sorry for my english. I had the same problem. Look [https://github.com/joeferner/node-java/issues/147]
my code:
`var java = require("java");
var path=require("path");
var fs=require("fs");
console.log("ruta in directory",path.join(__dirname));
console.log("exist file:",fs.existsSync(path.resolve(__dirname,"./lib-java/lib-tgd.jar")));
java.classpath.push("commons-lang3-3.1.jar");
java.classpath.push("commons-io.jar");
java.classpath.push(path.resolve(__dirname,"./lib-java/lib-tgd.jar"));
java.classpath.push(path.resolve(__dirname,"./lib-java/jackson-annotations- 2.5.1.jar"));
java.classpath.push(path.resolve(__dirname,"./lib-java/jackson-core-2.5.1.jar"));
java.classpath.push(path.resolve(__dirname,"./lib-java/jackson-databind-2.5.1.jar"));`
with path.resolve solves the problem of the file path

Resources