problem with reading path uploading a file in nodejs - node.js

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);

Related

React not recognizing Express

In my jsx file, I have the following:
var express = require('express');
var myExpress = express();
var http = require('http');
var app = http.createServer(myExpress);
var { Server } = require("socket.io");
var myio = new Server(app);
However, the browser says "Uncaught TypeError: express is not a function"
I have tried importing express with an import statement, as well as making my project a module in my package.json. What is weird is that when I use the same code in a regular js file in the same folder, it works perfectly well. This code was the code in every single one of the tutorials, so I am at a loss. Thank you.
Express is node framework you can't use it in react.
I think you need https://v5.reactrouter.com/web/guides/quick-start

Chart.js with 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

How to render a Log / text file in node js through url?

I am trying to view the log File in the browser on hitting a particular url. I have the log file in my local (/logsFolder/app.log)
I tried the following codes:
Code: 1
var app = express();
var path = require('path');
var logFile = require('/logs/app');
app.use('/logs',logFile);
It threw error like
Error: Cannot find module '/logs/app'
Code :2
const app = express();
const path = require('path');
const router = express.Router();
router.get('/logFile', function(req, res){
console.log("inside logt :");
res.render('./logs/app.log');
});
can anyone Please help me to resolve.
Your log is static text file, not a javascript, nor json file, that why you can't require it. (code 1)
You are not using template engine either, that's why your code 2 didn't work, It cannot be render by itself.
You can use the built in express middleware for static files.
Try this:
app.use(express.static('logsFolder'))
Now you can access all the content of logsFolder by requesting the file name. For example: http://your-url/app.log
Or try your code 2 with res.sendFile instead of res.render

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