var http = require("http");
function onRequest(request, response) {
console.log("Request received.");
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
this writes to console on a request from my chrome browser:
Request received
Request received
Two times? Why?
It was your browser asking for favicon.ico
Related
To show my students a simple HTTP request and response that they could capture using Wireshark, I whipped up a simple Node.js HTTP server:
var fs = require('fs');
var http = require('http');
var port = 80;
var file = process.argv[2]; //This file contains a 42 byte HTML page
http.createServer(function (req, res) {
res.writeHead(200, { 'content-type' : 'text/html' }); // Sends first packet
fs.createReadStream(file).pipe(res); // Sends second packet
}).listen(port);
Unfortunately, the two lines transmitting the HTTP header and the HTML are sent as two separate TCP packets (even though they are both quite small). It would be simpler for my students if the HTTP header and HTML were just one packet. How could I change my code to do this?
var http = require('http');
var fs = require('fs');
var file = process.argv[2];
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html;"});
fs.readFile(file, function (err, html) {
if (err) {
throw err;
}
response.write(html);
response.end();
});
}).listen(8000);
the reason it won't work is that Node.js runs everything asynchronously. When you are loading your html file, the server creation starts the same time. By the time you are about to write your html to your tcp socket, the file most likely won't be ready.
I see what you were trying to do before... I misread your code because of the indentation. Let me know if this snippet works.
try using something like-
var file = process.argv[2];
fs.readFile(file, function (err, html) {
if (err) {
throw err;
}
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(8000);
});
I'm learning node.js but am struggling with the fs.readFile function in my simple web server code (demo.js below). If I access http://localhost:8001/demo.html I get no data back in the browser, but if I access '/' or any other file name I see the "hello world' or 404 pages as expected.
I have included the content of demo.html and the node console output where the log messages suggest that the readFile is reading the file OK, but I get nothing in the browser and don't see the 'Got here D' log message.
I'm sure I must be missing something obvious but can't see what. Any help would be appreciated!
demo.js code:
var http = require("http");
var url = require('url');
var fs = require('fs');
var server = http.createServer(function(request, response){
console.log('Connection');
var path = url.parse(request.url).pathname;
switch(path){
case '/':
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('hello world');
break;
case '/demo.html':
fs.readFile(__dirname + path, function(error,data){
console.log("error: " + error);
console.log("data: " + data);
if (error){
console.log("Got here A");
response.writeHead(404);
response.write("oops problem loading this page - 404");
}
else{
console.log("Got here B");
response.writeHead(200, {"Content-Type": "text/html"});
response.write(data);
}
});
break;
default:
console.log("Got here C");
response.writeHead(404);
response.write("oops this page doesn't exist - 404");
break;
}
response.end();
console.log("Got here D");
});
server.listen(8001);
demo.html:
<html>
<body>This is my demo page</body>
</html>
node console output:
C:\code\Node>node demo.js
Connection
Got here D
error: null
data: <html>
<body>This is my demo page</body>
</html>
Got here B
The problem lies in the position of the response.end() call.
fs.readFile is an asynchronous function; like all functions in node related to I/O. This means that the reading of the file is done in a background process and when the data is available your defined callback function is called with the result.
Node continues to execute your code after fs.readFile, which results in response.end() being called before your callback function builds the response.
To fix this you have to move the response.end() call into the cases like this:
var http = require("http");
var url = require('url');
var fs = require('fs');
var server = http.createServer(function(request, response){
console.log('Connection');
var path = url.parse(request.url).pathname;
switch(path){
case '/':
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('hello world');
response.end();
break;
case '/demo.html':
fs.readFile(__dirname + path, function(error,data){
console.log("error: " + error);
console.log("data: " + data);
if (error){
response.writeHead(404);
response.write("oops problem loading this page - 404");
}
else{
response.writeHead(200, {"Content-Type": "text/html"});
response.write(data);
}
response.end();
});
break;
default:
response.writeHead(404);
response.write("oops this page doesn't exist - 404");
response.end();
break;
}
});
iam very new to nodejs. I found difficult with this server creation program
var http = require("http");
function onRequest(request, response) {
console.log("Request received.");
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
http.createServer(onRequest).listen();
You have to mention the port number to listen.
Your code has to have aport number in the listen.
http.createServer(onRequest).listen(8080);
The port number 8080 was already in use....So i used
another port number like 8083....It works...
I'm learning Node.js can created a hello world server, here is the code server.js
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8888);
I can access localhost:8888 from my server machine but I can't access ip:8888 from another machine and I also can't access domainname:8888. What is the problem?
On nodejs.org socket.setTimeout, it says
When an idle timeout is triggered the socket will receive a 'timeout' event but the connection will not be severed.
But when I test code like this:
var http = require('http');
server = http.createServer(function (request, response) {
request.socket.setTimeout(500);
request.socket.on('timeout', function () {
response.writeHead(200, {'content-type': 'text/html'});
response.end('hello world');
console.log('timeout');
});
});
server.listen(8080);
The socket is closed immediately after timeout, and no data is replied to the browser. Which is quite different from the document. Is this a bug or is there any tricks dealing socket under http module?
The documentation is indeed correct, however it looks like the http module adds a 'timeout' listener which calls socket.destroy(). So what you need to do is get rid of that listener by calling request.socket.removeAllListeners('timeout').
So your code should look like:
var http = require('http');
server = http.createServer(function (request, response) {
request.socket.setTimeout(500);
request.socket.removeAllListeners('timeout');
request.socket.on('timeout', function () {
response.writeHead(200, {'content-type': 'text/html'});
response.end('hello world');
console.log('timeout');
});
});
server.listen(8080);