I'm getting a reoccuring error that crashes my program.
In the program, I'm consistantly making async requests (one by one I should say)
to download specific images off the internet, this is my code for the request:
const urlDownload = (uri, filename, callback) => {
try {
console.log('start url');
console.log(uri);
request.head(uri, function(err, res, body){
if(err) {
console.log('request error!');
console.log(err);
} else {
request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
console.log('end url');
}
// console.log('content-type:', res.headers['content-type']);
// console.log('content-length:', res.headers['content-length']);
});
} catch(e) {
console.log('urlDownload issue');
console.log(e);
}
}
Now, sometimes it doesn't crash, but I feel like 50% or more of the times it does with this exact error:
node:events:368
throw er; // Unhandled 'error' event
^
Error: aborted
at connResetException (node:internal/errors:691:14)
at TLSSocket.socketCloseListener (node:_http_client:407:19)
at TLSSocket.emit (node:events:402:35)
at node:net:687:12
at TCP.done (node:_tls_wrap:580:7)
Emitted 'error' event on Request instance at:
at Request.onerror (node:internal/streams/legacy:62:12)
at Request.emit (node:events:390:28)
at IncomingMessage.<anonymous> (/home/mrz/Desktop/DEVELOPMENT/node_modules/request/request.js:1079:12)
at IncomingMessage.emit (node:events:390:28)
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
code: 'ECONNRESET'
}
I don't know what to do, tried to search about it and found nothing really,
nothing wrong with the URL it tries to download too!
based on the console logs I have made, it seems like it crashes AFTER it ends the request process successfully I think, because I do get the output, and then it crashes, that's just speculations, I have no idea what's going on.
Related
This code is producing an error in spite of a try-catch block... It should send a error message, if the server isn't reachable and a positive message, if ist is.
try {
net.connect(25565, "mc.hypixel.net", () => {
console.log("connected");
});
} catch (err) {
console.log("not connected");
}
This is the error:
events.js:292
throw er; // Unhandled 'error' event
^
Error: connect ETIMEDOUT 104.16.78.21:25565
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16)
Emitted 'error' event on Socket instance at:
at emitErrorNT (internal/streams/destroy.js:106:8)
at emitErrorCloseNT (internal/streams/destroy.js:74:3)
at processTicksAndRejections (internal/process/task_queues.js:80:21) {
errno: -4039,
code: 'ETIMEDOUT',
syscall: 'connect',
address: '104.16.78.21',
port: 25565
}
Thank you for your help :)
hmm.. I believe the following answer is what net suggests
try this
net.connect(25565, "mc.hypixel.net", () => {
console.log("connected");
})
.on('error', (err)=>console.log("not connected"));
I am trying write to google sheet using 'google-spreadsheet' via Next.js API route. It works perfectly fine when I am testing locally. I can see the data being updated in the google sheet. However, when I deploy it to Vercel, it doesn't work. The 'Functions' log from Vercel shows the following error message.
Error authentication FetchError: request to https://www.googleapis.com/oauth2/v4/token failed, reason: Client network socket disconnected before secure TLS connection was established
at ClientRequest. (/var/task/node_modules/node-fetch/lib/index.js:1461:11)
at ClientRequest.emit (events.js:315:20)
at TLSSocket.socketErrorListener (_http_client.js:469:9)
at TLSSocket.emit (events.js:315:20)
at emitErrorNT (internal/streams/destroy.js:106:8)
at emitErrorCloseNT (internal/streams/destroy.js:74:3)
at processTicksAndRejections (internal/process/task_queues.js:80:21) {
type: 'system',
errno: 'ECONNRESET',
code: 'ECONNRESET',
config: {
method: 'POST',
url: 'https://www.googleapis.com/oauth2/v4/token',
data: {
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
assertion: ....
Below is my code if that's any help.
export default async function addRowAPI(req, res) {
if (req.method === 'POST') {
try {
let doc;
try {
doc = new GoogleSpreadsheet(process.env.SPREADSHEET_ID);
} catch (error) {
console.log('error at line 15:', error);
}
try {
await doc.useServiceAccountAuth({
client_email: process.env.GOOGLE_SHEETS_CLIENT_EMAIL,
private_key: (process.env.GOOGLE_SHEETS_PRIVATE_KEY || '').replace(
/\\n/g,
'\n'
),
});
} catch (error) {
console.log('error authentication', error);
}
await doc.loadInfo();
console.log(doc.title);
const sheet = doc.sheetsByTitle['Test_Sheet'];
console.log(sheet.title);
console.log('addRow Doc:', doc);
const newRow = await sheet.addRow(req.body);
res.status(201).send();
} catch (error) {
res.status(500).json(error);
}
} else if (req.method === 'GET') {
res.status(200).json({ ping: 'pong' });
}
}
As mentioned in the comments, the error complains about an authentication issue which indicates wrong/non-existing credentials. Double-check you have all the environment variables properly set in Vercel.
I'm trying to catch mongodb disconnection event.
It works fine with the following setup:
simple.js
'use strict';
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/pnsockets', function () {
console.log('mongoose connected');
});
mongoose.connection.on('disconnected', function () {
console.log('mongoose disconnected');
});
If simple.js is running and I stop mongodb (launchctl stop homebrew.mxcl.mongodb), I get mongoose disconnected on the console, and I can handle the issue.
But running extended.js that is usung socket.io-adapter-mongo, when I kill mongodb, I get the following error:
/project/node_modules/mongoose/node_modules/mongodb/lib/utils.js:98
process.nextTick(function() { throw err; });
^
MongoError: server localhost:27017 timed out
at null.<anonymous> (/project/node_modules/mongodb-core/lib/topologies/server.js:436:40)
at emitTwo (events.js:87:13)
at emit (events.js:172:7)
at null.<anonymous> (/project/node_modules/mongodb-core/lib/connection/pool.js:144:10)
at g (events.js:260:16)
at emitTwo (events.js:87:13)
at emit (events.js:172:7)
at Socket.<anonymous> (/project/node_modules/mongodb-core/lib/connection/connection.js:172:12)
at Socket.g (events.js:260:16)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at TCP._onclose (net.js:468:12)
extended.js
'use strict';
var mongoose = require('mongoose');
var socketIO = require('socket.io');
var MongoAdapter = require('socket.io-adapter-mongo');
mongoose.connect('mongodb://localhost:27017/pnsockets', function () {
console.log('mongoose connected');
_setupSocketAdapter();
});
mongoose.connection.on('disconnected', function () {
console.log('mongoose disconnected');
});
var _setupSocketAdapter = function () {
var io = socketIO();
var socket = mongoose.connections[0].db;
socket.connection = mongoose.connections[0]; // mubsub will need this line
var mongoAdapter = MongoAdapter({socket: socket});
io.adapter(mongoAdapter);
};
How can I catch the MongoError: server localhost:27017 timed out error?
The problem is coming from socket.io-adapter-mongo itself.
If you take a look at the source code, they're using mubsub. Mubsub is basically a pub / sub implementation for Node.js and MongoDB.
They're setting up a client and a channel which is mapping one-to-one with a capped collection but there is no event handler attached on these parts.
According to the mubsub documentation, the following event are available on a channel: *, message, document, ready and error. The error event is also available on the client.
For example, simply adding the following code would catch the errors you're having.
channel.on('error', function (err) {
console.error(err.message);
});
client.on('error', function (err) {
console.error(err.message);
});
In case of a disconnection, you'll get the following output instead of the unhandled error.
mongoose connected
server localhost:27017 timed out
mongoose disconnected
Mubsub: broken cursor.
I have the following folder structure:
Inside of CacheModule.js i have the following code:
socket.on('saveUserCache', function (obj, user_id) {
var jsonOutput = JSON.stringify(obj);
if (!fs.existsSync('./cacheObjects/' + user_id)) {
fs.mkdirSync('./cacheObjects/' + user_id, 0777, function (err) {
if (err) {
console.log(err);
}
});
}
fs.writeFile('./cacheObjects/' + user_id + '/cache.json', jsonOutput, function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
});
The idea behind this is to check if the users folder exists (if not) create a new folder and then write to a file.
However im getting the following error:
Error: ENOENT: no such file or directory, mkdir './cacheObjects/125'
at Error (native)
at Object.fs.mkdirSync (fs.js:794:18)
at Socket.<anonymous> (/var/www/project/app_server/costum_modules/CacheModule.js:10:16)
at emitTwo (events.js:87:13)
at Socket.emit (events.js:172:7)
at Socket.onevent (/var/www/project/app_server/node_modules/socket.io/lib/socket.js:330:8)
at Socket.onpacket (/var/www/project/app_server/node_modules/socket.io/lib/socket.js:290:12)
at Client.ondecoded (/var/www/project/app_server/node_modules/socket.io/lib/client.js:193:14)
at Decoder.Emitter.emit (/var/www/project/app_server/node_modules/socket.io/node_modules/socket.io-parser/node_modules/component-emitter/index.js:134:20)
at Decoder.add (/var/www/project/app_server/node_modules/socket.io/node_modules/socket.io-parser/index.js:247:12)
at Client.ondata (/var/www/project/app_server/node_modules/socket.io/lib/client.js:175:18)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at Socket.onPacket (/var/www/project/app_server/node_modules/socket.io/node_modules/engine.io/lib/socket.js:99:14)
at emitOne (events.js:82:20)
at WebSocket.emit (events.js:169:7)
Can anyone tell me why this is happening. it looks like its sending mkdir with the string. Also i have given the right permissions (so it is not lacking permissions)
I m running an Express 4 application, and I added some logic to router:
router.get('/pars', function(req, res, next) {
fetcher.parseXml(function(err, result){ //download files from ftp server, it can takes from 10 sec to 1 minute
if(err) {
console.log("router " + err);
res.render('index', { title: err });
}else {
console.log(result);
res.render('index', { title: 'Download finish' });
}
});
});
And added coressponding button to start index page, that send ajax to that '/pars' endpoint:
...
<button id="btn">Parse Data</button>
<script>
$( document ).ready(function() {
$('#btn').click(function () {
$.get(
"/pars",
onAjaxSuccess
);
});
function onAjaxSuccess(data) {
alert(data);
};
});
</script>
So all works fine and I sucesfully reloading page and downloading files from ftp using 'jsftp' module, but after some time (it may be 30 sec or 2 minutes ) I got error which crash all my app:
events.js:85
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at exports._errnoException (util.js:746:11)
at TCP.onread (net.js:559:26)
I found similar problem at Node js ECONNRESET
And added this 'catching' code to my app.js:
process.on('uncaughtException', function (err) {
console.error(err.stack);
console.log("Node NOT Exiting...");
});
Now app doesnt crashes, but spams that error from time to timeto my log, and all logic works fine.
I think issue can be in ftp.get:
Ftp.get(config.get("ftpDownloader:dir") + '/'+ fileName, __dirname + '/xml/' + fileName, function(hadErr) {
if (hadErr){
log.error('There was an error retrieving the file.' + hadErr);
ftpDonwloadCallback(hadErr);
}else{
log.info("XML WAS DOWNLOADED: " + fileName);
readFile(fileName, ftpDonwloadCallback);
}
});
Maybe somebody can help me how I can fix that problem?
depends on the error info:
events.js:85
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at exports._errnoException (util.js:746:11)
at TCP.onread (net.js:559:26)
it's caused by TCP connection. if the underlying socket receive a 'error' event, but no 'error' event listener, it will propagate and crash you process.
check your http server, add error event listener to it.
for example:
var server = http.createServer(function(request, response){ ... ... });
server.on('error', function(err) { ... ... });
if you want to catch the error from client, you can listener 'clientError' event.