My knowledge of node.js isn't very good and I might be missing something obvious.
I need to "crawl" a list of urls (combination of http-https, hosts and ports) for an experiment. One of those urls is not responding (it does locally, so I guess one of the middleboxes is blocking) it, which it's fine but I breaks my app as I'm not able to catch the error:
var http2 = require('http2');
var req = http2.raw.get('http://xxx.yyy.zzz.a:23/', function(response) {
var content = '';
response.on('data', function(chunk) {
content += chunk;
})
response.on('end', function() {
console.log(content);
console.log('end');
});
});
req.on('error', function(error) {
console.error(error);
});
It throws the following Error (catched it with process.on('uncaughtException', ...)):
{ [Error: connect ETIMEDOUT xxx.yyy.zzz.a:23]
code: 'ETIMEDOUT',
errno: 'ETIMEDOUT',
syscall: 'connect',
address: 'xxx.yyy.zzz.a',
port: 23 }
Error: connect ETIMEDOUT xxx.yyy.zzz.a:23
at Object.exports._errnoException (util.js:814:11)
at exports._exceptionWithHostPort (util.js:837:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1044:14)
Try-catch does not work, because the function is async.
request.on('error') does not seem to catch this error. setTimeout is not implemented in this library.
I think I need to add an event into the TCP connection, but I don't know how.
I'm using node.js 0.12.7 and http2 3.2.0
Any ideas? Really appreciated
Related
I am using request to access data from an api. sometimes, when the api Url is down, node throws error and shuts down with the following error
at ClientRequest.emit (events.js:315:20)
at TLSSocket.socketErrorListener (_http_client.js:426:9)
at TLSSocket.emit (events.js:315:20)
at emitErrorNT (internal/streams/destroy.js:92:8)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
errno: 'ENOTFOUND',
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: APIURL
is there any way to handle this and prevent node from exiting?
my code is
const JSONdata= ()=>{
request({url:API_URL2,json:true},(error,response,body)=>{
const data=[]
var jsondata=body
data.push(jsondata)
const data2=JSON.stringify(data)
fs.writeFile('sample.txt',data2,(err) => { if(error){console.log(error} })})
You can use try/catch blocks that will keep your program running when certain functions error out. Here's a link describing how they work!
https://www.w3schools.com/js/js_errors.asp
Firstly request module has been deprecated request deprecated hence you can try some other packages like axios. Also while trying out api as well as database request try to have a try and catch block and in case of error try to have an appropriate error message displayed to the user.
try{
//your code
res.json("success")
}
catch(err){
res.json("Looks like something went wrong")
}
I tried installing this package : https://github.com/FLYBYME/node-transmission in my local nodejs installation but I am getting following error while running example.js from the above github repository.
Error: connect ECONNREFUSED 127.0.0.1:9091
at Object.exports._errnoException (util.js:1022:11)
at exports._exceptionWithHostPort (util.js:1045:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1090:14)
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 9091
After a bit research I tried to run a server at port 9091 using this code(in a separate server.js file)
const http = require('http')
const port = 9091
const requestHandler = (request, response) => {
console.log(request.url)
response.end('Hello Node.js Server!')
}
const server = http.createServer(requestHandler)
server.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
})
After running a server on port 9091, I started getting this error with example.js :
SyntaxError: Unexpected token H in JSON at position 0
at JSON.parse (<anonymous>)
at IncomingMessage.onEnd (F:NodeJS\node-transmission-master\lib\transmission.js:453:33)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
What must be causing this? I have no idea which step I have done wrong. That's why I described the whole process I followed.
I am very new to nodejs. Any help will be deeply appreciated.
The library is expecting a JSON formatted response and you are sending a simple text response. If you look through their source code you can see that their callServer function expects a stringified JSON but I can't see that in their docs.
You can change your code like so:
const http = require('http')
const port = 9091
const requestHandler = (request, response) => {
console.log(request.url)
// Format your response as a stringified JSON
response.end(JSON.stringify({message: 'Hello Node.js Server!'}));
}
const server = http.createServer(requestHandler)
server.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
})
In order to run the example from the node-transmission package, you need first to install and start the transmission-daemon.
The following steps are for Ubuntu:
Login as root or change to root with su - (be always careful what you do/install as root)
Install the transmission-daemon linux package: apt-get install transmission-daemon
Edit the daemon configuration for either disabling authentication or setting up your username/password (there is no default password). You can disable authentication by editing the relative flag in the configuration file:
pico /etc/transmission-daemon/settings.json
Set the auth flag to false: rpc-authentication-required:false
Press Ctrl-X then Y and then Enter to save the change
Start the daemon: start transmission-daemon
You should be able now to execute successfully the example.js and download its torrent link.
When I run app.js, I get this error:
MBPdiDaniele3:Desktop danielemartini$ node app.js
events.js:141
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED 127.0.0.1:8080
at Object.exports._errnoException (util.js:870:11)
at exports._exceptionWithHostPort (util.js:893:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1063:14)
MBPdiDaniele3:Desktop danielemartini$
Here's the code for make_request.js:
var http = require('http');
var makeRequest = function(message) {
var options = {
host: 'localhost', port: 8080, path:'/', method: 'POST'
}
var request = http.request(options, function(response) {
response.on('data', function(data) {
console.log(data);
});
});
request.write(message);
request.end();
};
module.exports = makeRequest;
Here's the code for app.js:
var makeRequest = require('./make_request');
makeRequest("Here's looking at you, kid");
makeRequest("Hello, this is dog");
There are several possible causes :
No service is running on localhost:8080
A service runs on 8080 which refuses connections actively.
To check what is running, use one of those 2 commands (Unix) :
lsof -i :8080 -S
netstat -a | grep 8080
3 - Your running service isn't bound to your internal IP.
I've encountered the issue a few times on Cloud servers, where localhost/127.0.0.1 are not recognized. Try using the external IP of your machine (and make sure the firewall lets you make requests), or force your service to bind to all interfaces.
Hope it helps.
I have the C# app that sends the UDP packets for the specific IP and port and it works well, because I have the other app that receives those packages. Now I would like to send them so that I can display it on my webpage - I've read that the node.js will fit perfectly here.
I installed the current version of node.js under windows environment and took the following code:
var PORT = 19777;
var MULTICAST_GROUP = "224.0.0.251";
var dgram = require("dgram");
var client = dgram.createSocket("udp4");
client.on("message", function(message, rinfo) {
console.log("received: ",message,rinfo);
});
client.on("listening", function() {
console.log("listening on ",client.address());
client.setBroadcast(true);
client.setTTL(64);
client.setMulticastTTL(64);
client.setMulticastLoopback(true);
client.addMembership(MULTICAST_GROUP);
client.send(payload, 0, payload.length, PORT, MULTICAST_GROUP, function(err,bytes) {
console.log("err: "+err+" bytes: "+bytes);
// client.close();
});
});
client.on("close", function() {
console.log("closed");
});
client.on("error", function(err) {
console.log("error: ",err);
});
client.bind(19777);
And now I started sending packets on the following ip "224.0.0.251" and port 19777 from my C# app - however, after runnint the client app I've got the following error:
C:\Users\user\Desktop>node client.js
error: { [Error: bind EADDRINUSE] code: 'EADDRINUSE', errno: 'EADDRINUSE', sysc
all: 'bind' }
What am I doing wrong? And - after fixing this issue - will I be able to just see all packets in the console? Thanks.
------------- EDIT:
Following the advice of John, I modified the app so that only node.js is listening now on that port. Thanks to this I made a progress and on the output of my console I get:
C:\Users\user\Desktop>node client.js
listening on { address: '0.0.0.0', family: 'IPv4', port: 19777 }
C:\Users\user\Desktop\client.js:19
client.send(payload, 0, payload.length, PORT, MULTICAST_GROUP, function(er
^
ReferenceError: payload is not defined
at Socket.<anonymous> (C:\Users\godyckim\Desktop\client.js:19:17)
at Socket.emit (events.js:104:17)
at startListening (dgram.js:139:10)
at dgram.js:230:7
at dns.js:85:18
at process._tickCallback (node.js:355:11)
at Function.Module.runMain (module.js:503:11)
at startup (node.js:129:16)
at node.js:814:3
but still no packets are visible.. Ok, I see that I didn't define the payload variable... What I want to achieve is to receive the packets that are sent by udp and either display it in the node.js console (that would be a start for me), or transfer it further so that I can see them in the browser. In the second case - what exactly I'm doing wrong now? Thanks!
I've been working through the learnyoujs and stream-adventure tutorials:
https://github.com/substack/stream-adventure
https://github.com/rvagg/learnyounode#learn-you-the-nodejs-for-much-win
I've gotten all the way through the first set and most of the way thorough the second, but I keep getting an odd error... usually I can get it to go away.
Here's the command/error:
DEV/javascript/streamAdventure ยป stream-adventure run httpserver.js
stream.js:94
throw er; // Unhandled stream error in pipe.
^
Error: connect ECONNREFUSED
at errnoException (net.js:901:11)
at Object.afterConnect [as oncomplete] (net.js:892:19)
This will launch but not kill the process for node, so I ps aux | grep node and then find the process and kill it.
Here's the "working" code from the tutorial:
var http = require('http');
var through = require('through');
var server = http.createServer(function (req, res) {
if (req.method === 'POST') {
req.pipe(through(function (buf) {
this.queue(buf.toString().toUpperCase());
})).pipe(res);
}
else res.end('send me a POST\n');
});
server.listen(8000);
If I just run nod httpserver.js and then curl at it, it works fine.... so does anyone have any insight into what is causing this error?
There is a pull request to fix this, here:
https://github.com/substack/stream-adventure/pull/16
Try to listen on port 8001 instead and rerun verify after closing all processes listening on 8000.
I had the same error, problem wasn't with though node however, it was with mysql.
Ran "mysqld_safe restart" (depends on your version), then it worked fine.