I'm trying to read log file when it's change and emit changes(this part work)
The problem is I get an error :
(node:7088) UnhandledPromiseRejectionWarning: Error: EBUSY: resource busy or locked, open './temp.log'
at Object.openSync (fs.js:457:3)
at new LineByLine (C:\Users\Server\Documents\rconMinecraft\node_modules\n-readlines\readlines.js:23:26)
at myLineReader (C:\Users\Server\Documents\rconMinecraft\node_modules\text-file-diff\index.js:22:15)
at TextFileDiff.diff (C:\Users\Server\Documents\rconMinecraft\node_modules\text-file-diff\index.js:63:25)
at Diff (C:\Users\Server\Documents\rconMinecraft\app.js:56:7)
at Change (C:\Users\Server\Documents\rconMinecraft\app.js:40:3)
at FSWatcher. (C:\Users\Server\Documents\rconMinecraft\app.js:32:7)
at FSWatcher.emit (events.js:321:20)
at FSWatcher.emitWithAll (C:\Users\Server\Documents\rconMinecraft\node_modules\chokidar\index.js:521:8)
at FSWatcher._emit (C:\Users\Server\Documents\rconMinecraft\node_modules\chokidar\index.js:613:10)
(node:7088) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was
not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:7088) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I now this error is because the file './temp.log' is already open. I looked for an alternative of my code but I did not find.
My code :
const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
const express = require('express');
const fs = require('fs');
var chokidar = require('chokidar');
app.use('/public', express.static('public'));
app.get('/', function(req, res) {
res.sendFile(__dirname + '/views/index.html');
});
var watcher = null;
var _Socket = null;
var path = 'C:/Users/Server/Downloads/Serv/logs/latest.log';
io.sockets.on('connection', function(socket) {
_Socket = socket;
});
WatchFile();
http.listen(80, function() {
console.log('listening on *:80');
});
function WatchFile() {
watcher = chokidar.watch(path, {
persistent: false
});
watcher
.on('change', path => {
Change();
})
}
function Change() {
fs.copyFile(path, './temp.log', (err) => {
console.log('this is a test');
});
Diff();
}
function Diff() {
var TextFileDiff = require('text-file-diff');
var d = new TextFileDiff();
d.on('compared', (line1, line2, compareResult, lineReader1, lineReader2) => { /*console.log(line1 + " ////// " + line2);*/ });
d.on('-', line => {
console.log('File 1 : ' + line);
});
d.on('+', line => {
console.log('File 2 : ' + line);
_Socket.emit('message', line);
});
d.diff(path, './temp.log');
}
Related
I am facing an error with node/express. I am assuming the issue is with my asynchronous code design.
Output:
Success in container
Expected Output:
Success in container..
Success in Uploading...
Error: (node:18364) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()
DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Code:
const express = require("express");
const multer = require("multer");
const AuthReq = require("../middleWare/AuthReq");
require("dotenv").config();
const Azure_Storage_Connection_String = process.env.Azure_Connection_String;
const { BlobServiceClient } = require("#azure/storage-blob");
const Router = express.Router();
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "uploads");
},
filename: function (req, file, cb) {
cb(null, Date.now() + "-" + file.originalname);
},
});
const upload = multer({ storage: storage });
Router.post("/profile", AuthReq, upload.single("profile"), async (req, res) => {
const file = req.file;
const blobServiceClient = BlobServiceClient.fromConnectionString(
Azure_Storage_Connection_String
);
const containerName = req.user._id;
const ContainerClient = blobServiceClient.getContainerClient(containerName);
try {
const containerResponse = await ContainerClient.create();
} catch (err) {
return res.status(400).send("Error while sending image");
}
res.send("Success in container");
const contentType = file.mimetype;
const filePath = file.path;
const blobName = file.filename + contentType;
const blockBlobClient = ContainerClient.getBlockBlobClient(blobName);
try {
const uploadBlobResponse = await blockBlobClient.uploadFile(filePath);
} catch (err) {
return res.status(400).send("Error while sending image");
}
res.send("Success in Uploading...");
});
module.exports = Router;
You cannot use res.send more than once per request, because one request has only one response. I assume that you want to send a "two-part" response, so that the user first sees "Success in container" and then (a few seconds later) "Success in Uploading ...".
Node.js will send the response in two "chunks" if you use
res.write("Success in container");
...
res.end("Success in Uploading...");
(See also the explanation in this answer.)
I was making CRUD APIs with NodeJS, ExpressJS, and Mongoose, on executing the following code I got an UnhandledPromiseRejectionWarning error for line number 29. Despite having a try-catch block.
Code:
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
require('../src/db/conn.js');
const MensRanking = require('../src/models/mens.js');
app.use(express.json());
app.get('/', async (req, res) =>{
res.send("<h1>Hello World!</h1>");
})
app.post('/mens', async (req, res) =>{
try{
const addingMensRecords = new MensRanking(req.body);
console.log(req.body);
const insert = await addingMensRecords.save();
res.sendStatus(201).send(insert);
}
catch(e){
res.sendStatus(400).send(e);
}
})
app.get('/mens', async (req, res) =>{
try{
const getMens = await MensRanking.find({});
res.sendStatus(201).send(getMens);
}
catch(e){
res.sendStatus(400).send(e);
}
})
app.listen(port,()=>{
console.log(`\nlistening at http://127.0.0.1:${port}\n`);
})
Error:
(node:20016) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:518:11)
at ServerResponse.header (D:\projects\rest-api-sections\rest-tute\node_modules\express\lib\response.js:771:10)
at ServerResponse.contentType (D:\projects\rest-api-sections\rest-tute\node_modules\express\lib\response.js:599:15)
at ServerResponse.sendStatus (D:\projects\rest-api-sections\rest-tute\node_modules\express\lib\response.js:357:8)
at D:\projects\rest-api-sections\rest-tute\src\app.js:29:13
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:20016) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:20016) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Here is the complete code repository
You should use res.status instead of sendStatus
Difference between response.status() vs. response.sendStatus() in express
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
require('../src/db/conn.js');
const MensRanking = require('../src/models/mens.js');
app.use(express.json());
app.get('/', async (req, res) => {
res.send('<h1>Hello World!</h1>');
});
app.post('/mens', async (req, res) => {
try {
const addingMensRecords = new MensRanking(req.body);
console.log(req.body);
const insert = await addingMensRecords.save();
res.status(201).send(insert);
}
catch (e) {
res.status(400).send(e);
}
});
app.get('/mens', async (req, res) => {
try {
const getMens = await MensRanking.find({});
res.status(201).send(getMens);
}
catch (e) {
res.status(400).send(e);
}
});
app.listen(port, () => {
console.log(`\nlistening at http://127.0.0.1:${port}\n`);
});
You are using sendStatus function of epxress.js as it immediately sends that particular assigned code to the response object which triggers response before your data is set, so when your send function is called response object has already been sent, hence the error:
Cannot set headers after they are sent to the client
Instead, use this when you need to set HTTP Response codes as well alongside data
res.status(RESPONSE_CODE).send(DATA)
There are two problematic function in this case i just highlight one, because they have the same errors:
app.post('/mens', async (req, res) =>{
try{
const addingMensRecords = new MensRanking(req.body);
console.log(req.body);
const insert = await addingMensRecords.save();
res.sendStatus(201).send(insert);
}
catch(e){
res.sendStatus(400).send(e);
}})
You already sent a response in your try-block with res.sendStatus(201) and trying to send again with .send(insert) -> throws exception
After that you do the same error again with res.sendStatus(400).send(e);
The following code should do what you tried to intend:
app.post('/mens', async (req, res) =>{
try{
const addingMensRecords = new MensRanking(req.body);
console.log(req.body);
const insert = await addingMensRecords.save();
res.status(201).send(insert);
}
catch(e){
res.status(400).send(e);
}})
homePage.create is not working. i think my problem is here
"mongoose.connect('mongo://localhost:27017/Socialuser', { useNewUrlParser: true, useUnifiedTopology: true });"
App.js file
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
let homePage = require('./models/home');
mongoose.connect('mongo://localhost:27017/Socialuser', { useNewUrlParser: true, useUnifiedTopology: true });
const app = express();
app.use(express.static(__dirname + '/public'));
app.get('/', (req, res) => {
res.render('landing.ejs');
});
app.get('/login', (req, res) => {
res.render('loginSignUp.ejs');
});
app.get('/home', (req, res) => {
console.log(homePage);
homePage.create({ name: 'wasim', image: 'https://www.w3schools.com/w3css/img_lights.jpg' }, (err, home) => {
if (err) {
console.log(err);
} else {
console.log('saved');
}
});
});
app.listen(3000, () => {
console.log('server started at port 3000');
});
here is my home.js file.it's the home schema file
const mongoose = require('mongoose');
let homePageSchema = new mongoose.Schema({
name: String,
image: String
// comments: [ String ]
});
module.exports = mongoose.model('Home', homePageSchema);
what is the actual problem i didn't getting what is going on. 'UnhandledPromiseRejectionWarning: MongoParseError: Invalid connection string' .....this problem is going
(node:22464) UnhandledPromiseRejectionWarning: MongoParseError: Invalid connection string
at parseConnectionString (C:\Users\wasim\Desktop\social\node_modules\mongodb\lib\core\uri_parser.js:547:21)
at connect (C:\Users\wasim\Desktop\social\node_modules\mongodb\lib\operations\connect.js:277:3)
at C:\Users\wasim\Desktop\social\node_modules\mongodb\lib\mongo_client.js:222:5
at maybePromise (C:\Users\wasim\Desktop\social\node_modules\mongodb\lib\utils.js:662:3)
at MongoClient.connect (C:\Users\wasim\Desktop\social\node_modules\mongodb\lib\mongo_client.js:218:10)
at C:\Users\wasim\Desktop\social\node_modules\mongoose\lib\connection.js:713:12
at new Promise (<anonymous>)
at NativeConnection.Connection.openUri (C:\Users\wasim\Desktop\social\node_modules\mongoose\lib\connection.js:710:19)
at Mongoose.connect (C:\Users\wasim\Desktop\social\node_modules\mongoose\lib\index.js:335:15)
at Object.<anonymous> (C:\Users\wasim\Desktop\social\app.js:6:10)
at Module._compile (internal/modules/cjs/loader.js:1133:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:10)
at Module.load (internal/modules/cjs/loader.js:977:32)
at Function.Module._load (internal/modules/cjs/loader.js:877:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
(node:22464) UnhandledPromiseRejectionWarning: Unhandled promise rejection.
This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
(node:22464) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
1) Please use this
mongodb://localhost:27017/Socialuser
Instead of -
mongo://localhost:27017/Socialuser
2) mongoose.connect("mongodb://localhost:27017/[yourDbName]", {
useUnifiedTopology: true,
useNewUrlParser: true
});
In your case yourDbName = Socialuser
Hope this will solve your problem!
I have a form and I am trying to validate it with express-validator. When there are no validation errors, I get no error in the console, but when there are validation errors I try to pass them to my EJS template, but it gives me an error in the console. This is my full code:
var express = require('express');
var app = express();
var path = require('path');
var mongoose = require('mongoose');
var bodyParser = require('body-parser')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}))
const { check, validationResult } = require('express-validator');
app.listen(8080);
// saytin asuma inch template piti ogtagorcvi
app.set('view engine', 'ejs');
// MongoDB
let dbUrl = 'mongodb+srv://grig:xxxXXXxxx#cluster0-osvfl.mongodb.net/test?retryWrites=true&w=majority';
mongoose.connect(dbUrl ,{useNewUrlParser : true},(err) => {
if (err) {
console.log(err);
}
});
var schema = new mongoose.Schema({ name: 'string', message: 'string' });
var User = mongoose.model('User', schema);
//
// router
app.get('/', function(req, res) {
res.render('index');
});
app.use(express.json());
app.post('/send', [
check('name').isLength({ min: 1 }).withMessage('Անունը չի կարող դատարկ լինել'),
check('message').isLength({ min: 10 }).withMessage('Նամակը պետք է լինի 10 սիմվոլից ավել')
], (req, res) => {
// Uxarkel errornery
const errors = validationResult(req);
if (!errors.isEmpty()) {
res.render('index',{
errors: errors
});
}
// Stexcel userin
User.create({
name: req.body.name,
message: req.body.message
}).then(user => res.json(user));
});
//
And here's the error that I'm getting:
(node:6244) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:470:11)
at ServerResponse.header (C:\xampp\htdocs\node\node_modules\express\lib\response.js:771:10)
at ServerResponse.send (C:\xampp\htdocs\node\node_modules\express\lib\response.js:170:12)
at ServerResponse.json (C:\xampp\htdocs\node\node_modules\express\lib\response.js:267:15)
at User.create.then.user (C:\xampp\htdocs\node\server.js:51:23)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:6244) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecti
ng a promise which was not handled with .catch(). (rejection id: 1)
(node:6244) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process wit
h a non-zero exit code.
I'm new to Node, so can you please explain what causes the error. Thanks.
if (!errors.isEmpty()) {
res.render('index',{
errors: errors
});
}
else {
// Stexcel userin
User.create({
name: req.body.name,
message: req.body.message
}).then(user => res.json(user))
}
The else part of code was getting executed, even if there was error, and it was trying to send the response again. thus you were getting that error. Or you can a return when you are sending error, it will resolve the issue.
I need make a conversion of a Multer Midware function('upload') using callback to works in async mode using promises.
I tried to transform the upload function in a promise.
The image sent to server continues being saved as before, but my code throw an error as:
(node:3568) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): undefined
(node:3568) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the
Node.js process with a non-zero exit code.
when I execute the function
var resp=await uploadAsync(req, res);
What am I doing wrong?
//server code
'use strict';
const express = require('express');
const router = express.Router();
const pool = require('./pool'); // my database pool module, using promise-mysql
const Errors = require('./mysql_errors'); // my collection of custom exceptions
const HttpStatus = require('http-status-codes');
var path = require('path')
var fs = require('fs')
const fileDir='./public/images/uploads'
//imagens
const multer = require('multer');
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, fileDir)
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' + file.originalname);
}
})
const upload = multer({ storage: storage}).single('foto');
function uploadAsync(req,res){
return new Promise(function(resolve,reject){
upload(req,res,function(err){
if(err !== null) return reject(err);
resolve();
});
});
}
router.post('/foto/:id',uploadAsync, async function(req,res,next){
try{
var resp=await uploadAsync(req, res);
}catch(err) {
return res.status(500).send({ success:false, message: 'Erro', results:{} }); // 404
}
});
module.exports=router;
if(err !== null) return reject(err);
resolve();
in those conditions, you have to keep like
if(err !== undefined) return reject(err);
resolve();
as the error will be undefined is the call back returns true.