John
John

Reputation: 11

running html in javascript server with node.js

Here is my Javascript code...

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

var port = '2405';

function send404Response(response){
  response.writeHead(404, {"Content_Type": "text/plain"});
  response.write("Error 404: Page not found!");
  response.end();  
}

function onRequest(request,response){
  if(request.method == 'GET' && request.url == '/'){
    response.writeHead(200, {"Content-Type": "text/html"});
    fs.createReadStream("./index.html").pipe(response);
  } else{
    send404Response(response);
  }
}

http.createServer(onRequest).listen(port);
console.log("Server is now running...");

When I write node /Users/SurajDayal/Documents/ass2/app.js in terminal and go to http://localhost:2405/ the terminal gives the error....

events.js:160 throw er; // Unhandled 'error' event ^

Error: ENOENT: no such file or directory, open './index.html' at Error (native)

Directory structure:

Folder Layout

Upvotes: 0

Views: 133

Answers (2)

NineBerry
NineBerry

Reputation: 28499

Use

var path = require('path');
fs.createReadStream(path.join(__dirname, "index.html")

Your version does not work because the relative path is relative to the current working directory (the current directory in the console when you start node), not relative to the script file.

__dirname gives the directory of the current script file.

Upvotes: 0

Brad
Brad

Reputation: 163262

You're probably starting your application from another directory. The relative path here to ./index.html is going to be relative to the current working directory.

If you want to go relative to the current running file, try __dirname:

fs.createReadStream(__dirname + '/index.html').pipe(response);

Also, if you need to do anything much more complicated for HTTP serving, check out Express. There's a nice module for your static files, but it also is a nice utility for routing and other common functions needed for HTTP apps.

Upvotes: 1

Related Questions