I am new to nodeJS. I am trying to load an index.html page onto my 8080 port and have this:
var http = require('http');
var fs = require('fs');
var PORT = 8080;
function home(req, res) {
if(req.url == '/'){
fs.readFile('index.html', function read (err, data) {
res.writeHead(200, {'Content-type' : 'text/html'});
res.write(data);
res.end();
});
}
};
var server = http.createServer(function (req, res) {
home(req, res);
});
server.listen(PORT);
I have 3 files in the same directory: index.html, style.css, server.js. I start up the server and the page will not load until after I hit cntrl + c. Why is this?
You have written the data to the response, but you have not finished the response. Put res.end(); after your res.write function.
Without this, the browser keeps waiting for more data from the server. When you shut down the server with Ctrl-C, the server closes the connection, and the browser renders what it received.
If you are new to Node, I would recommend looking into something like Express, which handles a lot of important things like routing (what URLs go to which pages) for you and will save you a lot more if statements in the future.
Related
I'm tring to read this file in nodejs using fs module.
I'm getting the response twice. let me know what am i doing wrong. Here's my code.
var http = require("http");
var fs = require("fs");
http.createServer(function(req, res) {
fs.readFile('sample.txt', function(err, sampleData) {
console.log(String(sampleData));
//res.end();
});
console.log("The end");
// res.writeHead(200);
res.end();
}).listen(2000);
After hitting the port in browser. I'm getting the response twice in my terminal. Here's the output.
The end
this is sample text for the testing.
The end
this is sample text for the testing.
You are most likely getting it twice because you are accessing http://localhost:2000/ from the browser.
When doing so there are actually two requests being made. Your actual request and the favicon :) both of which are handled by your server.
Have a look into Chrome debugger -> Network
Two log messages will appear: one for / and one for /favicon.ico
You can verify this by adding console.log(req.url);
To avoid this:
var http = require("http");
var fs = require("fs");
http.createServer(function(req, res){
if(req.url === '/'){ // or if(req.url != '/faicon.ico'){
fs.readFile('sample.txt', function(err , sampleData){
console.log(String(sampleData));
res.end();
});
console.log("The end");
}
// res.writeHead(200);
}).listen(2000);
A request is made to favicon.io automatically.
To avoid automatic request to favicon, you can do the following
http.createServer(function(req, res){
if(req.url != '/favicon.ico'){
fs.readFile('sample.txt', function(err , sampleData){
console.log(String(sampleData));
res.end();
});
console.log("The end");
}
}).listen(2000);
O/p =>
The end.
this is sample text for the testing.
You may pipe the file to the client:
fs.createReadStream('sample.txt').pipe(res);
I want to create a simple Node.js server and send data with pipe() method. But I have an issue.
The page loads when server started the first time, but when I refresh the page, it becomes blank. I mean the data is not loaded. Why does it happen?
var http = require('http'),
fs = require('fs');
var myReadStream = fs.createReadStream(__dirname + '/input.txt', 'utf8');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
myReadStream.pipe(res);
}).listen(3300);
This would work if you change it to:
http.createServer(function (req, res) {
var myReadStream = fs.createReadStream(__dirname + '/input.txt', 'utf8');
res.writeHead(200, {'Content-Type': 'text/plain'});
myReadStream.pipe(res);
}).listen(3300);
That's because the stream once read is not rewinded automatically (in fact it cannot be).
But it's not the most flexible way to serve static content.
See this answer for five examples of serving static files with and without Express, from using high-level frameworks to very low level manual reinventing the wheel kind of implementation.
How to serve an image using nodejs
I am new to Node.js, so I figured I would check it out and do a hello world. I have been having the same issue on all three of my machines, a Win 8, Win 7 and a Mac. Thought at first it was a firewall issue, but I checked and it was off on both Mac and Windows 8 machines (didn't bother checking the win7). When I run Node from the terminal the browser waits for localhost, then eventually times out. I have been at this for two days, can't seem to find any solution via Google. What am I missing.?
Here is my code:
var http = require("http");
console.log("file loaded");
http.createServer(function (request, response) {
request.on("end", function () {
response.writeHead(200, {
'Content-Type': 'text/plain'
});
response.end('Hello HTTP!');
});
}).listen(8080);
You don't need to wait for the HTTP request to end (besides that request.on('end', ..) isn't valid and never fires, and that's why you time out). Just send the response:
var http = require("http");
console.log("file loaded");
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello HTTP!');
}).listen(8080);
Although if you want an easier way to create a HTTP server, the simplest way would be to use frameworks such as Express. Then your code would look like this:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.set('Content-Type', 'text/plain');
res.send(200, 'Hello HTTP!');
});
app.listen(8080);
You can also use the connect middleware. Just install it first using npm like so:
npm install -g connect
After this you can make a very simple app like this:
var app = connect()
.use(connect.logger('dev'))
.use(connect.static('public'))
.use(function(req, res){
res.end('hello world\n');
})
.listen(3000);
You can get more information regarding connect here. I tell you to use this, because you get a very simple server, that is easily extensible. However, if you want to make pull blown web sites, then I would sugges using expressjs.
I am trying to learn the ins and outs of node. I know you can serve a file with a framework but I am trying to do it manually. I have a jpeg file in './public/logo.jpg'. When I send the request through localhost:8080 I don't get the image, just a blank screen with a generic image placeholder. What am I doing wrong? Thanks!
var http=require('http');
var url=require('url');
var fs=require('fs');
// creates a new httpServer instance
http.createServer(function (req, res) {
// this is the callback, or request handler for the httpServer
log('in server callback')
res.ins=res.write;
var parse=url.parse(req.url,true);
var path0=parse.pathname;
console.log(path0)
// respond to the browser, write some headers so the
// browser knows what type of content we are sending
var serveFile=function(){
var path='./public'+path0
fs.exists(path,function(e){
if(e){
log('serving file')
log(path)
fs.readFile(path,'binary',function(err,data){
if(data){
res.writeHead(200, {'Content-Type': 'image/jpeg'});
res.ins(data)
res.end()
}
})
}
else{
log('no file to serve')
log(path)
servePage()
}
})
}
serveFile()
}).listen(8080); // the server will listen on port 8080
Simply change the following two lines in your readFile callback :
res.writeHead(200, {'Content-Type': 'image/jpeg'});
res.write(data, 'binary');
Use response.write to send data to the client and set encoding to binary. (Default is utf-8)
I just setup a basic node.js server with socket.io on my local machine. Is there a way to set a document root so that you can include other files. Ie. Below I have a DIV with a a background image. The path the image is relative to the location of the server, however this is not working. Any ideas? Thanks!
var http = require('http'),
io = require('socket.io'), // for npm, otherwise use require('./path/to/socket.io')
server = http.createServer(function(req, res){
// your normal server code
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<div style="background-image:url(img/carbon_fibre.gif);"><h1>Hello world</h1></div>');
});
server.listen(8080);
// socket.io
var socket = io.listen(server);
Use Express or Connect. Examples: https://github.com/spadin/simple-express-static-server, http://senchalabs.github.com/connect/middleware-static.html
For the background-image style, browser will create a entirely new HTTP Request to your server with path *img/carbon_fibre.gif*, and this request will certainly hit your anonymous function, but your response function only write back a div with ContentType: text/html regardless the req.pathname so that the image cannot be properly displayed.
You may add some code to your function like:
var http = require('http'),
io = require('socket.io'),
fs = require('fs'),
server = http.createServer(function(req, res){
// find static image file
if (/\.gif$/.test(req.pathname)) {
fs.read(req.pathname, function(err, data) {
res.writeHead(200, { 'Content-Type': 'image/gif' });
res.end(data);
});
}
else {
// write your div
}
});
server.listen(8080);
I'm not very familiar with nodejs, so the code above only demonstrates a logic but not the actual runnable code block.