No emit() method to be Called - node.js

I am learning Nodejs right now. I am confused to a partial of code from a textbook.
var http = require('http');
var querystring = require('querystring');
var server = http.createServer().listen(8124);
server.on('request', function(request,response) {
if (request.method == 'POST') {
var body = '';
// append data chunk to body
request.on('data', function (data) {
body += data;
});
// data transmitted
request.on('end', function () {
var post = querystring.parse(body);
console.log(post);
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World\n');
});
}
});
console.log('server listening on 8214');
http.createServer returns a http.Server object which inherits from EventEmitter.
To be sure, The EventEmitter contain on and emit method. In this example, I only see the on method, and do not find any place to call the emit method. How the emit method is called or the event bind on on method is triggered? Does the emit method encapsulates in other method?

emit function is not required to be called in this case. you can simply hit your url via postman.

Related

Testing a simple GET request from NodeJS

For testing purpose,I want to call a method (that does GET request) as soon as the server is created. I have the below code.
var rp = require('request-promise');
var http = require('http');
var URLSplunk = MY_URL
var headersSplunk = {
'Authorization': 'Bearer MY_AUTH',
'Cache-Control': 'no-cache',
'X-Requested-By': 'BABEL_FISH',
'client': 'slack'
};
function testSplunk(){
var optionsSplunk = {
url: URLSplunk,
headers: headersSplunk,
json: true
};
rp(optionsSplunk)
.then(function (resultReply) {
console.log("Splunk GET success")
console.log(resultReply)
})
.catch(function (error) {
console.log(`Error: \n${error}`);
});
}
http.createServer(function (request, response) {
testSplunk()
}).listen(3000);
console.log('Server started');
I was expecting to see the GET result or error but I only see 'Server started' message.
What am I missing?
My comment echo'd in greater detail by #jfiend00.
The way you have the code now, your testSplunk() function will get called only when your http server gets a request. It's inside the http server requestListener callback. So, you have to send the http server a request to trigger that callback so the testSplunk() function gets called.
The testSplunt() function is never being called by the program until a request is made to the server.
Putting it after the requestListener callback will allow for it to be executed in the manner that you want it to be.
E.g.
http.createServer(function (request, response) {
//This function is called when the server gets a request
//Process request.......
}).listen(3000);
testSplunk();
console.log('Server started');

Want to write capture and re-transmit http/https request to Browser?

I want to write a simple Node Js application which will capture and re-transmit http/https request to Browser?
I have written the below code, but it works only for http request.
var server = http.createServer(function (req,res) {
console.log("start request:", req.url);
var option = url.parse(req.url);
option.headers = req.headers;
var proxyrequest = http.request(option, function (proxyresponce) {
proxyresponce.on('data', function (chunk) {
console.log("proxy responce length" ,chunk.length);
res.write(chunk,'binary');
});
proxyresponce.on('end',function () {
console.log("proxy responce ended");
res.end();
});
res.writeHead(proxyresponce.statusCode, proxyresponce.headers);
});
});

Node.js, mongodb returning a string representation of a function, not the output

I am new to the world of mongodb and node.js .
I have a project in which I put the mongodb code in a routes, and I require it in my server.js.
now in that module I have one method that will return all entries in one collection ( it works ).
I am trying to call that function from the server.js file, but I usually end up with the response printing out the function, not executing it and returning the output!!
Example :
var http = require('http'),
location = require('./routes/locations');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write(location.findAll() + '');
response.end();
}).listen(8080);
Now when I direct my UI to 8080, I want to get the output of location.findall, instead I get an undefined message, and in node the following exception :
TypeError: Cannot call method 'send' of undefined
I know this is probably a newbie question, I am coming from java, .NET, and iOS world. sorry!!
update : To clarify more, here is what I have in routes/locations.js
var mongo = require('mongodb');
var Server = mongo.Server,
Db = mongo.Db,
BSON = mongo.BSONPure;
var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('locationsdb', server);
db.open(function(err, db) {
// initlization code
});
exports.findAll = function(req, res) {
db.collection('locations', function(err, collection) {
collection.find().toArray(function(err, items) {
res.send(items);
});
});
};
You need to actually call the function!
I'll guess findAll is async, so you should use the function in async manner
I don't know what is in your route/locations file, but it probably should look like this:
var http = require('http'),
location = require('./routes/locations');
http.createServer(function (request, response) {
location.findAll(function(err, locations) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write(locations);
response.end();
});
}).listen(8080);
I'm not sure, but try
response.write(location.findAll() + '');

Node.js Simple Server Request End Event Issue

I'm new to node.js. Trying to get a console to print when the request ends. I try to go to localhost:8080 and also localhost:8080/ but nothing prints in the terminal. Any idea why? Doing this because when I run this example because when I try to run the demo at http://tutorialzine.com/2012/08/nodejs-drawing-game/ the terminal says socket started but it does not render the index.html page. So I can't figure out why this code to serve static files for other is not working for me.
var static = require('node-static');
//
// Create a node-static server instance to serve the './public' folder
//
// var file = new(static.Server)('./');
require('http').createServer(function (request, response) {
request.addListener('end', function () {
console.log("ended");
});
}).listen(8080);
It seems that your are using Node.js 0.10.x and in the new version you have to resume the readable streams to make them emit events:
require('http').createServer(function (request, response) {
var body = '';
request.setEncoding('utf8');
request.on('readable', function () {
body+= this.read();
}
request.on('end', function () {
console.log('ended');
console.log('Body: ' + body);
});
request.resume();
}).listen(8080);
You should be call node-static serve inside the request handler so that you can get index.html
var static = require('node-static');
var fileServer = new static.Server('./');
require('http').createServer(function (request, response) {
fileServer.serve(request, response); //add this line
request.addListener('end', function () {
console.log("ended");
});
}).listen(8080);

Unable to set headers in node.js in POST method

I have a case where i have to read the data from the request body and create a file and write the data into it. If the operation is successful I set the response header to 201 and add the location of file in Location header. The file creation is done using Java methods and node.js code is below.
var server = http.createServer(function(req, res)
{
var body = "";
req.on("data", function(chunk)
{
body += chunk.toString();
});
req.on("end", function() {
var rtn = obj.AddonPostMethod(filepath,body);
if(rtn.length < 13)
{
res.writeHead(201, {"Location" : rtn});
res.end();
}
else
{
res.writeHead(400, {"Content-Type" : application/json"});
res.write(''+rtn);
res.end();
}
});
}});
The problem is that the response headers are not getting updated and are always set to the default headers 200 Ok. In addition to this the server is always busy even after the response is received.
I don't think you're actually listening on a port with the code you reference.
var http = require('http');
http.createServer(function(req,res){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
You never declare the http object as actually listening on a port/ip with the .listen() function.
Also, you don't need to wait for the req object to emit anything to respond. The function is called when the request is complete. You can listen for specific requests and route them appopriately by storing the http.Server object to a variable.
var server = http.createServer();
server.listen(8000);
server.on('request', function(req,res){ /* do something with the request */ });
More documentation on the http object can be found on the node.js documents for http

Resources