How to get status from Monit from a NodeJS program? - node.js

I'm trying to get the status from Monit from a NodeJS program. In my monitrc I have it set to use port 2812, but I'm not sure what to do in my node program. Any advice would be highly appreciated.
I'll add that I am currently clueless, but I've tried:
var net = require('net');
var client = net.connect({port: 2812},
function() { //'connect' listener
console.log('client connected');
client.write('monit status');
});
client.on('data', function(data) {
console.log(data.toString());
client.end();
});
client.on('end', function() {
console.log('client disconnected');
});
Which outputs:
client connected
HTTP/1.0 400 Bad Request
Date: Tue, 04 Dec 2012 17:03:15 GMT
Server: monit 5.3.2
Content-Type: text/html
Connection: close
<html><head><title>Bad Request</title></head><body bgcolor=#FFFFFF><h2>Bad Request</h2>Cannot parse request<p><hr><a href='http://mmonit.com/monit/'><font size=-1>monit 5.3.2</font></a></body></html>
client disconnected
This is more than nothing, since it actually lists monit as the server, but I have no idea how to make it work.

I figured it out. Turns out what I wanted to do was:
var http = require('http');
var options = {
hostname: '127.0.0.1',
port: 2812,
method: 'GET'
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (data) {
console.log('BODY: ' + data);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.end();

Related

A ECONNREFUSED error of the node. Js

My Node app is throwing a ECONNREFUSED error. The port should not be in use. Any ideas?
console.info('-----http-----');
console.info();
var http = require('http');
var options = {
hostname: 'localhost',
port: 6860,
path: '/',
method: 'post'
};
var req = http.request(options, function(res) {
console.log('status:' + res.statusCode);
res.setEncoding('UTF-8');
res.on('data', function(chunk) {
console.log('body:' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request:' + e.message);
});
req.end();
Seems you are trying to send post request to one of the URL (localhost),
the code you posted that alone will not work, somewhere your server should run i.,e localhost:6860
For that just you need to create a server which runs on the port 6860.
Execute this simple server.js file in separate terminal then run "localhost:6860" in your browser.
Then run your code in separate terminal, it will execute properly. Check your both terminals you will get the difference.
**server.js**
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
console.log(req.url)
console.log(req.method)
res.end('okay');
}).listen(6860, "localhost");
$node server.js
Hope it will help you..!

nodejs websocket detect disconnected socket

I have a nodejs websocket server and I have the following problem.
When my clients connect to the server and terminate gracefully the onclose method is called on those sockets and I perform clean up operations on the closed socket.
When the client disconnects due to network, the onclose method is not called. Is there any timeout to be set so onclose is called automatically after a timeout?
I am using ws package for the websocket server in nodejs
default ws implementation doesn't have a callback for network disconnects from client side
You can find a keepAlive implementation here
Well I'll try to answer your question with two examples. Try to analyze both of them and learn how they work. They are both tested and working.
1- Websocket:
Server:
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
server.listen(3000, function() {
console.log((new Date()) + ' Server is listening on port 3000');
});
wsServer = new WebSocketServer({
httpServer: server,
autoAcceptConnections: false
});
function originIsAllowed(origin) {
return true;
}
wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
request.reject();
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
return;
}
var connection = request.accept('echo-protocol', request.origin);
console.log((new Date()) + ' Connection accepted.');
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
connection.sendUTF(message.utf8Data);
}
else if (message.type === 'binary') {
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
connection.sendBytes(message.binaryData);
}
});
connection.on('close', function(reasonCode, description) {
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
});
});
Client:
<!DOCTYPE html>
<html>
<head>
<title>Web socket Experiment</title>
<script type="text/javascript">
function callWebSocket() {
var socket = new WebSocket("ws://localhost:3000", 'echo-protocol');
socket.onopen = function () {
alert("Hello, Connected To WS server");
};
socket.onmessage = function (e) {
alert("The message received is : " + e.data);
};
socket.onerror = function (e) {
alert("An error occured while connecting... " + e.data);
};
socket.onclose = function () {
alert("hello.. The coonection has been clsoed");
};
}
</script>
</head>
<body>
<input type="button" value="Open Connecton" onclick="callWebSocket()" />
</body>
</html>
2- Socket.io:
Server:
var http = require('http');
var app = require('express')();
var httpServer = http.createServer(app)
var io = require('socket.io')(httpServer);
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function(socket) {
socket.emit('news', {
hello: 'world'
});
socket.on('my other event', function(data) {
console.log(data);
});
socket.on('disconnect', function(data) {
console.log('disconnect!');
});
});
httpServer.listen(3000);
Client:
<html>
<head>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
var conn_options = {
'sync disconnect on unload':false
};
var socket = io.connect('http://localhost:3000',conn_options);
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
</head>
<body>
</body>
</html>
To detect a disconnect, you need to have some traffic. If your application produces constant traffic, then you could do something like reset a counter each time something is received, and consider the connection failed when the counter runs out.
Otherwise you should be able to use the pings that WebSocket offers. These are not exposed in the browser, but your WebSocket library for Node.js may allow you to turn them on and get a notification if a ping fails.
You can check it in the official library documentation. I don't want to copy-paste it here because it can be out of date soon.

Nodejs: response.write() for https.request?

Hi I am trying to make an https.request to an API server. I can receive the chunk and print it in the console. How can I write it directly into html and show it in the browser?
I tried to look for the equivalent of response.write() of http.request but didn't find one. res.write(chunk) will give me a TypeError. How can I do this?
var req = https.request(options_places, function(res){
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function(chunk){
console.log('BODY: ' + chunk); // Console can show chunk data
res.write(chunk); // This gives TypeError: Object #<IncomingMessage> has no method 'write'
});
});
req.end();
req.on('error', function(e){
console.log('ERROR?: ' + e.message );
});
First you have to create server and listen on some port for the requests.
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Whatever you wish to send \n');
}).listen(3000); // any free port no.
console.log('Server started');
Now it listens incoming connections at 127.0.0.1:3000
For specific url use .listen(3000,'your url') instead of listen(3000)
This works for me.
app.get('/',function(req, res){ // Browser's GET request
var options = {
hostname: 'foo',
path: 'bar',
method: 'GET'
};
var clientRequest = https.request(options, function(clientResponse){
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
clientResponse.setEncoding('utf8');
clientResponse.on('data', function(chunk){
console.log('BODY: ' + chunk);
res.write(chunk); // This respond to browser's GET request and write the data into html.
});
});
clientRequest.end();
clientRequest.on('error', function(e){
console.log('ERROR: ' + e.message );
});
});

forward proxy in nodejs

i made a small forward proxy with nodejs and hosted it in appfog.
it's working in local after setting up the proxy of my browser, but when i try using the one hosted in appfog it's says:
*Errore 130 (net::ERR_PROXY_CONNECTION_FAILED): Connessione al server proxy non riuscita.*
this is my code:
var http = require('http');
http.createServer(function(request, response) {
http.get(request.url, function(res) {
console.log("Got response: " + res.statusCode);
res.on('data', function(d) {
response.write(d);
});
res.on('end', function() {
response.end();
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
}).listen(8080);
Am i missing something?
your code is working but once i've tried using it like this:
var port = process.env.VCAP_APP_PORT || 8080;
var http = require('http');
var urldec = require('url');
http.createServer(function(request, response) {
var gotourl=urldec.parse(request.url);
var hosturl=gotourl.host;
var pathurl=gotourl.path;
var options = {
host: hosturl,
port: 80,
path: pathurl,
method: request.method
};
http.get(options, function(res) {
console.log("Got response: " + res.statusCode);
res.on('data', function(d) {
response.write(d);
});
res.on('end', function() {
response.end();
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
response.write("error");
response.end();
});
}).listen(port);
console.log(port);
It's still doesn't work: i got request timed out when i try to ping the address, i got the same ERR_PROXY_CONNECTION_FAILED... locally work but when i using the remote address as proxy it doesn't
First: The app needs to use the port number issued to it by cloudfoundry. The app sits behind a reverse proxy that takes incoming requests on port 80 and forwards them to the VCAP_APP_PORT.
var port = process.env.VCAP_APP_PORT || 8080; // 8080 only works on localhost
....
}).listen(port);
Then you access your hosted app like this:
http://<app_name>.<infra>.af.cm // port 80
And your local app:
http://localhost:8080
Second: You may need to use a options hash to send to the http.get method instead of just supplying the request.url.
var options = {
host: '<host part of url without the protocal prefix>',
path: '<path part of url>'
port: 80,
method: 'GET' }
I tested the following code on my local box and on AppFog and the IPs were different. Whatismyip returned my local interent ip address when running locally and on the AppFog hosted app it returned the AppFog server ip.
var port = process.env.VCAP_APP_PORT || 8080;
var http = require('http');
var options = {
host: "www.whatismyip.com",
port: 80,
path: '/',
method: 'GET'
};
http.createServer(function(request, response) {
http.get(options, function(res) {
console.log("Got response: " + res.statusCode);
res.on('data', function(d) {
response.write(d);
});
res.on('end', function() {
response.end();
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
response.write("error");
response.end();
});
}).listen(port);

Difficulties with node.js proxy

I am attempting to make a GET request for a single image on another server from node.js.
var http = require('http');
var site = http.createClient(80, '192.168.111.190');
var proxy_request = site.request('/image.png');
proxy_request.on('response', function (proxy_response) {
console.log('receiving response');
proxy_response.on('data', function (chunk) {
});
proxy_response.on('end', function () {
console.log('done');
});
});
And even with this code, I can't get the "receiving response" message to print out. Outside of node, I can do a curl http://192.168.111.190/image.png just fine, but is there something else I might be missing?
for get requests try the http.get API http://nodejs.org/docs/v0.4.9/api/http.html#http.get
var http = require('http');
var options = {
host: '192.168.111.190',
port: 80,
path: '/image.png'
};
http.get(options, function(res) {
console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
console.log("Got error: " + e.message);
});

Resources