If I want to write the result inside callback function to response, but I can't access the res variable in the function, and also I can't access the result outside the function.
So how to pass value between inside and outside?
var http = require('http');
var url = require('url');
http.createServer
(
function (req, res)
{
var output='';
res.writeHead(200, {'Content-Type': 'text/plain'});
//The url we want is: 'www.random.org/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
var options = {
host: 'www.random.org',
path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
};
callback = function(response) {
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
console.log(str);
//output+=str; //get result
});
}
http.request(options, callback).end();
//output+=str; //get result
res.end(output);
}
).listen(80, '127.0.0.1');
ver2
var http = require('http');
var url = require('url');
http.createServer
(
function (req, res)
{
var output='';
res.writeHead(200, {'Content-Type': 'text/plain'});
//The url we want is: 'www.random.org/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
var options = {
host: 'www.random.org',
path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
};
callback = function(response) {
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
res.write('inside');
});
}
http.request(options, callback).end();
res.write('outside');
res.end(output);
}
).listen(80, '127.0.0.1');
ver3
var http = require('http');
var url = require('url');
http.createServer
(
function (req, res)
{
res.writeHead(200, {'Content-Type': 'text/plain'});
//The url we want is: 'www.random.org/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
var options = {
host: 'www.random.org',
path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
};
callback = function(res) {
var str = '';
//another chunk of data has been recieved, so append it to `str`
res.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved, so we just print it out here
res.on('end', function () {
res.write('inside');
//or
this.write('inside');
});
}
http.request(options, callback).end();
res.write('outside');
res.end();
}
).listen(80, '127.0.0.1');
ver4
var http = require('http');
var url = require('url');
http.createServer
(
function (req, res)
{
res.writeHead(200, {'Content-Type': 'text/plain'});
//The url we want is: 'www.random.org/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
var options = {
host: 'www.random.org',
path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
};
callback = function(response) {
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
res.write('inside');
});
}
http.request(options, callback);
res.write('outside');
res.end();
}
).listen(80, '127.0.0.1');
You can't. The function that sets up the callback will have finished and returned before the callback executes. If it didn't, then the callback wouldn't be needed.
Do whatever work you need to do in the callback itself, not in the parent function.
I can't access the res variable in the function
You should be able to. It is still in scope.
(Although if you call end() on it before the callback runs, then breakage should be expected).
Related
I am a beginner with node so excuse me if this question is too obvious. Also I tried the official documentation but I could resolve this problem.
My node server is communicating with an external api through a service.
This is what I ve got so far in my service api-service.js :
var http = require('http');
exports.searchNear = function(lat, long, next){
var options = {
host: '1xx.xx.1xx.1x',
path: '/api/v1/geo,
method: 'GET'
};
var req = http.request(options, function(res) {
var msg = '';
res.setEncoding('utf8');
res.on('data', function(chunk) {
msg += chunk;
});
res.on('end', function() {
console.log(JSON.parse(msg));
});
});
req.on('error', function(err) {
// Handle error
});
req.write('data');
req.end();
var mis = 'hello';
next(null, mis);
}
At this moment I can get the Json and log it in the console. But I want to store the returned json in a variable so I could pass in the next() callback.
I tried to add a callback to the end event like:
exports.searchNear = function(lat, long, next){
....
.....
var req = http.request(options, function(res) {
.....
res.on('end', function(callback) {
console.log(JSON.parse(msg));
callback(msg);
});
});
....
req.end('', function(red){
console.log(red);
});
}
Thank you in advance.
The callback's name in your code should be "next":
var http = require('http');
exports.searchNear = function(lat, long, next) {
var options = {
host: '1xx.xx.1xx.1x',
path: '/api/v1/geo,
method: 'GET'
};
var req = http.request(options, function(res) {
var msg = '';
res.setEncoding('utf8');
res.on('data', function(chunk) {
msg += chunk;
});
res.on('end', function() {
console.log(JSON.parse(msg));
next(null, msg);
});
});
req.on('error', function(err) {
// Handle error
});
req.write('data');
req.end();
}
And then you should use your function like this:
searchNear(myLong, myLat, function (err, mesg) {
console.log('your JSON: ', mesg)
});
I may be misunderstanding your question but the obvious solution is to store your parsed json in a variable and pass the variable to next()
var parsed = JSON.parse(msg);
I know how http request works and I know how to send and receive response.
This is the sample code of http request.
var http = require('http');
var options = {
host: 'www.nodejitsu.com',
path: '/',
port: '1337',
method: 'POST'
};
callback = function(response) {
var str = ''
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log(str);
});
}
var req = http.request(options, callback);
req.write("hello world!");
req.end();
In my site everything working fine Server B send request to server A and server A response to server B. But, one time I face a problem when there is huge no of traffic on server A and it was unable to receive any request from server B which halt the whole process.
So is there is any error block in request to handle this type of errors ?
I googled alot and try this type of foolish things but it does not work for me
callback = function(response,error) {
if(error){
console.log(error)
}else{
var str = ''
response.on('data', function (chunk) {
str += chunk;
});
response.on('error', function (err) {
console.log(err);
});
}
});
Have you tried this:
var req = http.request(options,callback);
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
as given here:
http://nodejs.org/api/http.html#http_http_request_options_callback
I'm writing a Node.js script that converts HTML files to ENML (Evernote Markup Language).
Now this script correctly converts an existing HTML file to the desired ENML output. Now, I have the following question:
Client will be sending an HTML file in JSON format. How do I listen for all incoming requests, take the JSON object, convert to ENML, and write back the response to the original request?
My code for this is as follows:
var fs = require('fs');
var path = require('path');
var html = require('enmlOfHtml');
var contents = '';
var contents1 = '';
fs.readFile(__dirname + '/index.html', 'utf8', function(err, html1){
html.ENMLOfHTML(html1, function(err, ENML){ //using Enml-js npm
contents1=ENML;
});
});
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.write(contents1);
}).listen(4567, "127.0.0.1");
Thanks!
I guess that the client will make POST requests to your server. Here is how you could get the send information:
var processRequest = function(req, callback) {
var body = '';
req.on('data', function (data) {
body += data;
});
req.on('end', function () {
callback(qs.parse(body));
});
}
var http = require('http');
http.createServer(function (req, res) {
processRequest(req, function(clientData) {
html.ENMLOfHTML(clientData, function(err, ENML){ //using Enml-js npm
contents1 = ENML;
res.writeHead(200, {'Content-Type': 'application/json'});
res.write(JSON.stringify(contents1));
});
});
}).listen(4567, "127.0.0.1");
You can use the Node's request module.
request('http://www.example.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
});
I have the following code:
var http = require('http')
,https = require('https')
,fs = require('fs'),json;
var GOOGLE_API_KEY = process.env.GOOGLE_API_KEY;
var FUSION_TABLE_ID = "1epTUiUlv5NQK5x4sgdy1K47ACDTpHH60hbng1qw";
var options = {
hostname: 'www.googleapis.com',
port: 443,
path: "/fusiontables/v1/query?sql=SELECT%20*%20"+FUSION_TABLE_ID+"FROM%20&key="+GOOGLE_API_KEY,
method: 'GET'
};
http.createServer(function (req, res) {
var file = fs.createWriteStream("chapters.json");
var req = https.request(options, function(res) {
res.on('data', function(data) {
file.write(data);
}).on('end', function() {
file.end();
});
});
req.end();
req.on('error', function(e) {
console.error(e);
});
console.log(req);
res.writeHead(200, {'Content-Type': 'application/json'});
res.end('Hello JSON');
}).listen(process.env.VMC_APP_PORT || 8337, null);
how do i return the json object rather then the 'Hello JSON'?
Don't store the received data in a file, put it in a local variable instead, and then send that variable in res.end():
var clientRes = res;
var json = '';
var req = https.request(options, function(res) {
res.on('data', function(data) {
json += data;
}).on('end', function() {
// send the JSON here
clientRes.writeHead(...);
clientRes.end(json);
});
});
Note that you have two res variables - one for the response you're sending back to your own clients, and one which is the response you're receiving from Google. I've called the former clientRes.
Alternatively, if you're just going to proxy the information unmodified, you can just put clientRes.write(data, 'utf8') inside the res.on('data') callback:
http.createServer(function (clientReq, clientRes) {
var req = https.request(options, function(res) {
res.on('data', function(data) {
clientRes.write(data, 'utf8');
}).on('end', function() {
clientRes.end();
});
clientRes.writeHead(200, {'Content-Type: 'application/json'});
clientReq.end().on('error', function(e) {
console.error(e);
});
});
I am running nodejs with rabbitmq example this is my code on node
var http = require('http');
var url = require('url');
var fs = require('fs');
var io = require('socket.io');
var context = require('rabbit.js').createContext();
var httpserver = http.createServer(handler);
var socketioserver = io.listen(httpserver);
socketioserver.sockets.on('connection', function(connection) {
var pub = context.socket('PUB');
var sub = context.socket('SUB');
connection.on('disconnect', function() {
pub.destroy();
sub.destroy();
});
// NB we have to adapt between the APIs
sub.setEncoding('utf8');
connection.on('message', function(msg) {
pub.write(msg);
});
sub.on('data', function(msg) {
connection.send(msg);
});
sub.connect('chat');
pub.connect('chat');
});
httpserver.listen(8080, '0.0.0.0');
// ==== boring detail
function handler(req, res) {
var path = url.parse(req.url).pathname;
switch (path){
case '/':
path = '/index.html';
case '/index.html':
fs.readFile(__dirname + '/index.html', function(err, data){
if (err) return send404(res);
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data, 'utf8');
res.end();
});
break;
default: send404(res);
}
}
function send404(res){
res.writeHead(404);
res.write('404');
res.end();
}
The problem is this
sub.connect('chat');
pub.connect('chat');
instead of 'chat'(the message queue name on rabbit) I need to pass a parameter in the url of the html page(subscriber) to node. So for example
sub.connect(myparam);
pub.connect(myparam);