Ashwin Hegde
Ashwin Hegde

Reputation: 867

Node and route management

I have written following code:

var http = require('http');
var fs = require('fs');

var fileName = 'site/index.html';
var encoding = 'utf-8';
var dataContent = "";

fs.readFile(fileName, encoding, function(error, data) {
    if(error) throw error;
    dataContent = data;
});

var requestListener = function(request, response) {
    response.writeHead(200, {
        'Content-Length': dataContent.length,
        'Content-Type': 'text/html',
        'connection': 'keep-alive',
        'accept': '*/*'
    });

    response.end(dataContent);
}

var server = http.createServer(requestListener, function(connect) {
    connect.on('end', function() {
        console.log('Server disconnected...');
    });
});

server.listen(8000, function() {
    console.log("Server is listening...");
});

I have 2 files in site directory:

 1. index.html
 2. aboutus.html

Step 1: I run the above code using node command as node runServer.js

Step 2: Now i have opened the browser and typed the following url

http://localhost:8000/

The browser is showing me the content of index.html correctly. And the index.html file contents some raw text and link to another file i.e. aboutus.html

Step3: When i click the click the link for aboutus.html the browser change the url into following

http://localhost:8000/aboutus.html

but the content of aboutus.html is not display, instead it shows me the content of index.html

I know that this is happening because the fileName variable content 'site/index.html'. So the browser is rendering the index.html content

How can i change this behavior? If i am not using express.js


Now, i made few changes in the following code:

var http = require('http');
var fs = require('fs');
var path = require('path');

var fileName = "site/index.html";
var encoding = 'utf-8';
var dataContent = "";

function readContentFile(fileName) {
    console.log(fileName);
    fs.readFile(fileName, encoding, function(error, data) {
        if(error) throw error;
        dataContent = data;
    });
}

readContentFile(fileName);

var requestListener = function(request, response) {

    filePath = request.url;    
    if(filePath!='/') {
        fileName = 'site' + filePath;
        readContentFile(fileName);
    }

    response.writeHead(200, {
        'Content-Length': dataContent.length,
        'Content-Type': 'text/html',
        'connection': 'keep-alive',
        'accept': '*/*'
    });

    response.end(dataContent);
}

var server = http.createServer(requestListener, function(connect) {



    connect.on('end', function() {
        console.log('Server disconnected...');
    });
});

server.listen(8000, function() {
    console.log("Server is listening...");
});

Still its not working, Is any thing wrong in my code. or i should go for express.js

Upvotes: 0

Views: 578

Answers (1)

generalhenry
generalhenry

Reputation: 17319

I created an example of a static server

take a look @ http://runnable.com/UUgnuT2wDj1UAGSe

var http = require('http');
var fs = require('fs');
var path = require('path');

http.createServer(function (req, res) {
  if (req.url === '/') {
    req.url = '/index.html';
  }
  var file = path.join(__dirname,req.url);
  path.exists(file, function (exists) {
    if (exists) {
      fs.stat(file, function (err, stats) {
        if(err) {
          throw err;
        }
        if (stats.isFile()) {
          res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
          fs.createReadStream(file).pipe(res);
        } else {
          res.writeHead(404);
          res.end('not found');
        }
      });
    } else {
      res.writeHead(404);
      res.end('not found');
    }
  });
}).listen( 8000 );

console.log('Server running on port ' + 8000);

note: this is using node 0.6.x the apis have changed a bit since then, fs.exists, instead of path.exists.

Upvotes: 1

Related Questions