Node.js, dgram.setBroadcast(flag) fails due to "EBADF" - node.js

I'm using Node.js 0.6.9, and am trying to send a datagram broadcast package. Code:
var sys = require('util');
var net = require('net');
var dgram = require('dgram');
var message = new Buffer('message');
var client = dgram.createSocket("udp4");
client.setBroadcast(true);
client.send(message, 0, message.length, 8282, "192.168.1.255", function(err, bytes) {
client.close();
});
Running the code:
$ node test.js
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: setBroadcast EBADF
at errnoException (dgram.js:352:11)
at Socket.setBroadcast (dgram.js:227:11)
at Object.<anonymous> (/home/letharion/tmp/collision/hello.js:25:8)
at Module._compile (module.js:444:26)
at Object..js (module.js:462:10)
at Module.load (module.js:351:32)
at Function._load (module.js:310:12)
at Array.0 (module.js:482:10)
at EventEmitter._tickCallback (node.js:192:41)
Some googling reveals that "EBADF" means "The socket argument is not a valid file descriptor". But I don't understand enough about the problem for that to be helpful.

First of all, you seem to have trouble understanding the format of the stacktrace, so let's clarify it before we go to the actual error that is thrown here.
Format of a node.js Stacktrace
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
This part is just the location where the internal NodeJS logic choked up and put out the error below:
The actual error stacktrace follows, it shows the deepest location in the callstack first, so going down in the stack trace, brings you up in the call hierachy, eventually leading you to the point in your code where everything began.
Error: setBroadcast EBADF
at errnoException (dgram.js:352:11)
at Socket.setBroadcast (dgram.js:227:11)
at Object.<anonymous> (/home/letharion/tmp/collision/hello.js:25:8)
at Module._compile (module.js:444:26)
at Object..js (module.js:462:10)
at Module.load (module.js:351:32)
at Function._load (module.js:310:12)
at Array.0 (module.js:482:10)
at EventEmitter._tickCallback (node.js:192:41)
First it fails in dgram.js on line 352, dgram.js is a internal node.js module abstracting the "low level" code. Line 352 is in a function containing generic logic for throwing errors.
It was called at dgram.js in line 227, after a failed if check which wraps the call to the wrapped native UDP sockets setBroadcast method.
Going up one more layer, we end up at your hello.js file on line 25 with the client.setBroadcast(true); call.
The rest is more node.js code resulting from the initial load of the hello.js file.
The actual Error
The error thrown by the native code which node.js wraps here is EBADF looking this up in conjunction with UDP gives us:
EBADF
The socket argument is not a valid file descriptor.
By going further down into the node.js rabbit hole, we end up in the udp wrapper, which wraps the uv wrapper for the actual C implementation, in the uv wrapper we find:
/*
* Set broadcast on or off
*
* Arguments:
* handle UDP handle. Should have been initialized with
* `uv_udp_init`.
* on 1 for on, 0 for off
*
* Returns:
* 0 on success, -1 on error.
*/
Leading us to the conclusion that your socket has not been initialized yet.
In the end, binding the socket via client.bind(8000) fixed the missing initialization and made the program run.

The method setBroadcast should be called on 'listening' event or passed as callback in bind method:
var socket = dgram.createSocket('udp4');
socket.on('listening', function(){
socket.setBroadcast(true);
});
socket.bind(8000);
OR:
var socket = dgram.createSocket('udp4');
socket.bind(8000, undefined, function() {
socket.setBroadcast(true);
});

It seems like the file descriptor is created only on bind or on send, and it's required before setBroadcast. You can call client.bind() with no parameter to bind to a random port before setting broadcast. Don't worry about using a random port, since it's done "lazily" when using client.send anyway.
var sys = require('util');
var net = require('net');
var dgram = require('dgram');
var message = new Buffer('message');
var client = dgram.createSocket("udp4");
client.bind();
client.setBroadcast(true);
client.send(message, 0, message.length, 8282, "192.168.1.255", function(err, bytes) {
client.close();
});

Related

Unhandled rejection TypeError when trying to promisify a node-mysql connection and query

I'm attempting to use bluebird's promisify with the node-mysql package. Node version is 4.2.4
var Promise = require('bluebird');
var mysqlClient = Promise.promisifyAll(require("mysql/lib/Connection").prototype);
Promise.promisifyAll(require("mysql/lib/Pool").prototype);
var connectionOptions = ({
host: 'localhost',
user: 'root',
password: '',
database: 'my_db'
});
var firstPost = "some sql here";
var results = [];
mysqlClient.connectAsync(connectionOptions).then(function(connection){
connection.query(firstPost, function(){
console.log('i reached line 26 of a node script. a minor miracle')
});
}).catch(function(err) {
console.log(err);
});
I get the error
[TypeError: Cannot read property 'socketPath' of undefined]
Stack trace:
Unhandled rejection TypeError: Cannot read property 'socketPath' of undefined
at Connection.connect (/vagrant/spam_smasher/node_modules/mysql/lib/Connection.js:87:32)
at Connection.tryCatcher (/vagrant/spam_smasher/node_modules/bluebird/js/release/util.js:11:23)
at Connection.ret [as connectAsync] (eval at <anonymous> (/vagrant/spam_smasher/node_modules/bluebird/js/release/promisify.js:184:12), <anonymous>:13:39)
at Object.<anonymous> (/vagrant/spam_smasher/bluebird.js:24:13)
at Module._compile (module.js:435:26)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:313:12)
at Function.Module.runMain (module.js:467:10)
at startup (node.js:136:18)
at node.js:963:3
Why am I getting this error and/or how could I debug it further? I tried to remote debug it but am not sure what I'm looking at when I get a few steps down the prototype chain. The Async functions do appear to be attached to the MysqlClient object.
Remore debugging reveals that the following section in node-mysql's Connection.js file is throwing the error :
if (!this._connectCalled) {
this._connectCalled = true;
// Connect either via a UNIX domain socket or a TCP socket.
this._socket = (this.config.socketPath)
? Net.createConnection(this.config.socketPath)
: Net.createConnection(this.config.port, this.config.host);
socketpath is not something you need to define when using node-mysql directly
It seems the Bluebird docs are out of date. They miss that you also need ConnectionConfig to be available and so this was missing in my code, causing the error.
I chose to abandon this problem to preserve my sanity. There is further discussion here and you may also want to check out mysql-promise

node.js - handling TCP socket error ECONNREFUSED

I'm using node.js with socket.io to give my web page access to character data served by a TCP socket. I'm quite new to node.js.
User ----> Web Page <--(socket.io)--> node.js <--(TCP)--> TCP Server
The code is mercifully brief:
io.on('connection', function (webSocket) {
tcpConnection = net.connect(5558, 'localhost', function() {});
tcpConnection.on('error', function(error) {
webSocket.emit('error', error);
tcpConnection.close();
});
tcpConnection.on('data', function(tcpData) {
webSocket.emit('data', { data: String.fromCharCode.apply(null, new Uint8Array(tcpData))});
});
});
It all works just fine in the normal case, but I can't guarantee that the TCP server will be there all the time. When it isn't, the TCP stack returns ECONNREFUSED to node.js - this is entirely expected and I need to handle it gracefully. Currently, I see:
events.js:72
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED
at errnoException (net.js:904:11)
at Object.afterConnect [as oncomplete] (net.js:895:19)
... and the whole process ends.
I've done a lot of searching for solutions to this; most hits seem to be from programmers asking why ECONNREFUSED is received in the first place - and the advice is simply to make sure that the TCP server is available. No discussing of handling failure cases.
This post - Node.js connectListener still called on socket error - suggests adding a handler for the 'error' event as I've done in the code above. This is exactly how I would like it to work ... except it doesn't (for me), my program does not trap ECONNREFUSED.
I've tried to RTFM, and the node.js docs at http://nodejs.org/api/net.html#net_event_error_1 suggest that there is indeed an 'error' event - but give little clue how to use it.
Answers to other similar SO posts (such as Node.js Error: connect ECONNREFUSED ) advise a global uncaught exception handler, but this seems like a poor solution to me. This is not my program throwing an exception due to bad code, it's working fine - it's supposed to be handling external failures as it's designed to.
So
Am I approaching this in the right way? (happy to admit this is a newbie error)
Is it possible to do what I want to do, and if so, how?
Oh, and:
$ node -v
v0.10.31
I ran the following code:
var net = require('net');
var client = net.connect(5558, 'localhost', function() {
console.log("bla");
});
client.on('error', function(ex) {
console.log("handled error");
console.log(ex);
});
As I do not have 5558 open, the output was:
$ node test.js
handled error
{ [Error: connect ECONNREFUSED]
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect' }
This proves that the error gets handled just fine... suggesting that the error is happening else-where.
As discussed in another answer, the problem is actually this line:
webSocket.emit('error', error);
The 'error' event is special and needs to be handled somewhere (if it isn't, the process ends).
Simply renaming the event to 'problem' or 'warning' results in the whole error object being transmitted back through the socket.io socket up to the web page:
webSocket.emit('warning', error);
The only way I found to fix this is wrapping the net stuff in a domain:
const domain = require('domain');
const net = require('net');
const d = domain.create();
d.on('error', (domainErr) => {
console.log(domainErr.message);
});
d.run(() => {
const client = net.createConnection(options, () => {
client.on('error', (err) => {
throw err;
});
client.write(...);
client.on('data', (data) => {
...
});
});
});
The domain error captures error conditions which arise before the net client has been created, such as an invalid host.
See also: https://nodejs.org/api/domain.html

Excepetion in data event handler binding on read stream

I am getting Error while attaching 'data' event handler on read stream.
If I place this handler at other place as mention in the code (before pipe), I don't see any exception.
Please help me, what is wrong here?
var Readable = require("stream").Readable;
var readStream = new Readable;
readStream.on('data',function(chunk){console.log(chunk);}); //Error
readStream.push('first data');
readStream.push('second data');
readStream.push(null);
//if I place data event handler here, no Error is seen
readStream.pipe(process.stdout);
//getting error while binding data event handler
events.js:72
throw er; // Unhandled 'error' event
^
Error: not implemented
at Readable._read (_stream_readable.js:446:22)
at Readable.read (_stream_readable.js:320:10)
at Readable.<anonymous> (_stream_readable.js:745:45)
at Readable.EventEmitter.emit (events.js:92:17)
at emitDataEvents (_stream_readable.js:771:10)
at Readable.on (_stream_readable.js:692:5)
at Object.<anonymous> (/home/pk/node/readableStream.js:12:12)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
You can't simply instantiate Readable stream, as it has no valid _read method implemented. If you want just to push some data to it (without performing real IO), just set it to noop:
readStream._read = function () {};

limestone module in Nodejs throwing error with nodejs and sphinx

I have been trying to connect sphinx server with nodejs and limestone module. But it is throwing error as follows. Please help me on this.
node.js:134
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: ENOENT, No such file or directory
at doConnect (net.js:549:5)
at Socket.connect (net.js:709:5)
at Object.createConnection (net.js:265:5)
at Object.connect (/home/node/node_modules/limestone/limestone.js:129:23)
at Object.<anonymous> (/home/node/www/bmchat-new/sphinx-connect.js:4:15)
at Module._compile (module.js:411:26)
at Object..js (module.js:417:10)
at Module.load (module.js:343:31)
at Function._load (module.js:302:12)
at Array.<anonymous> (module.js:430:10)
Source code of sphinx-connect.js
var limestone = require("limestone").SphinxClient(),
sys = require("sys");
limestone.connect("192.168.2.168:9312", // port. 9312 is standard Sphinx port. also 'host:port' allowed
function(err) { // callback
if (err) {
sys.puts('Connection error: ' + err);
}
sys.puts('Connected, sending query');
limestone.query(
{'query':'test', maxmatches:1},
function(err, answer) {
limestone.disconnect();
sys.puts("Extended search for 'test' yielded " +
answer.match_count + " results: " +
JSON.stringify(answer));
});
});
The issue is that i am using old limestone.js which i have got from npm(v1.0.106). So the updated one, you can get from github
Issue found is, old limestone.js using server_conn = tcp.createConnection(port); instead of the below one server_conn = tcp.createConnection(port, host);

process.nextTick error in node.js?

I am getting process.nextTick error on this very basic example of node.js.
Can someone please figure out?
Is node not able to start listening on port 8000?
# cat nodejs.js
net = require("net");
s = net.createServer();
net.on('connection', function (c) {
c.end('hello');
});
s.listen(8000);
# node nodejs.js
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Object #<Object> has no method 'on'
at Object.<anonymous> (/home/ec2-user/praveen/nodejs.js:4:5)
at Module._compile (module.js:432:26)
at Object..js (module.js:450:10)
at Module.load (module.js:351:31)
at Function._load (module.js:310:12)
at Array.0 (module.js:470:10)
at EventEmitter._tickCallback (node.js:192:40)
It's a typo in Ryan's slide! :-0
s/net.on/s.on/
It seems you're trying to capture an event on the library (net), but you should be looking at the connectionListener argument to createServer. Try this instead:
var net = require("net");
var server = net.createServer(function (c) {
c.end('Hello!'); // Implicitly fired on 'connection'
});
server.listen(8000);
For anyone else who might stumble here looking for why node pukes this error when they try to issue brunch watch --server, check and make sure you don't have any other servers running using the same port (i.e. in another shell).

Resources