Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Node.JS static file web server. Put it in your path to fire up servers in any directory, takes an optional port argument.
var http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs")
port = process.argv[2] || 8888;
http.createServer(function(request, response) {
var uri = url.parse(request.url).pathname
, filename = path.join(process.cwd(), uri);
path.exists(filename, function(exists) {
if(!exists) {
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
return;
}
if (fs.statSync(filename).isDirectory()) filename += '/index.html';
fs.readFile(filename, "binary", function(err, file) {
if(err) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
return;
}
response.writeHead(200);
response.write(file, "binary");
response.end();
});
});
}).listen(parseInt(port, 10));
console.log("Static file server running at\n => http://localhost:" + port + "/\nCTRL + C to shutdown");
@brandt1871
Copy link

brandt1871 commented Apr 15, 2015

Many thanks.

Shouldn't the method "exists" be used with fs instead of path?
On line 12 of the code we have:

path.exists(filename, function(exists) {...});

This gave me an error and it seemed fine after I replaced it with:

fs.exists(filename, function(exists) {...});

@einsiol
Copy link

einsiol commented Jun 7, 2015

Agree with the last comment, replacing path.exist with fs.exist fixed an error that I did not fully understand. Otherwise, fantastic solution, perfect for beginners :)

@raidenz
Copy link

raidenz commented Jun 23, 2015

yes thanks brandt1871 path.exists is now called fs.exists

@fordnox
Copy link

fordnox commented Jul 17, 2015

Same issue here, path.exists is now called fs.exists

Please fix for future generations :)

@ratneshnavlakhe
Copy link

ratneshnavlakhe commented Aug 24, 2015

Thanks!!!

@Deele
Copy link

Deele commented Sep 28, 2015

Please, include package.json so that we could npm install. Thanks!

@byeblogs
Copy link

byeblogs commented Nov 14, 2015

You saved my day brotha.. Thanks :) ~

@CustomsoftGH
Copy link

CustomsoftGH commented Jan 8, 2016

For those newbies out there, path.exists has been depricated to fs.exists.

@harismohammed
Copy link

harismohammed commented Jan 23, 2016

thank u

@evenfrost
Copy link

evenfrost commented May 18, 2016

If anyone is interested in ES6+ version, I've revamped it here.

@kostasx
Copy link

kostasx commented May 23, 2016

Small typo: fs = require("fs") is missing a comma at the end of the line, making port on the next line a global variable.
Thank you for sharing!

@archasek
Copy link

archasek commented Jun 9, 2016

Fixed the whole code. Enjoy :)

var http = require("http"),
    url = require("url"),
    path = require("path"),
    fs = require("fs"),
    port = process.argv[2] || 8888;

http.createServer(function(request, response) {

  var uri = url.parse(request.url).pathname
    , filename = path.join(process.cwd(), uri);

  fs.exists(filename, function(exists) {
    if(!exists) {
      response.writeHead(404, {"Content-Type": "text/plain"});
      response.write("404 Not Found\n");
      response.end();
      return;
    }

    if (fs.statSync(filename).isDirectory()) filename += '/index.html';

    fs.readFile(filename, "binary", function(err, file) {
      if(err) {        
        response.writeHead(500, {"Content-Type": "text/plain"});
        response.write(err + "\n");
        response.end();
        return;
      }

      response.writeHead(200);
      response.write(file, "binary");
      response.end();
    });
  });
}).listen(parseInt(port, 10));

console.log("Static file server running at\n  => http://localhost:" + port + "/\nCTRL + C to shutdown");

@CforED
Copy link

CforED commented Jul 4, 2016

Hi, Everyone:

Problem: There is a failure in the JavaScript code (server.js) to route a var to the following directory: ./public/index.html.

Symptoms: HTTP Error 403.14 - Forbidden.

Request for Support: What is the correct JavaScript to route var to a particular directory?

URL References:

1.) GitHub URL link: https://github.com/CforED/WebSite/blob/master/server.js

2.) Gist URL link: https://gist.github.com/CforED/177a2e73dfb87313576376fc00a2c9f4.js

3.) GitHub URL link to website:
https://github.com/CforED/WebSite/tree/master/public

Hal

@amejiarosario
Copy link

amejiarosario commented Aug 24, 2016

I created a new one that handles MIME types and uses ES6+

https://gist.github.com/amejiarosario/53afae82e18db30dadc9bc39035778e5

@kovid-rathee
Copy link

kovid-rathee commented Feb 3, 2017

Got an error with path.exists, changed it to fs.exists and the snippet worked fine.

@duluca
Copy link

duluca commented Feb 28, 2017

@kovid-rathee I ran in to the same issue and your solution worked!

@Julia991
Copy link

Julia991 commented Mar 28, 2017

Hey, guys what do you think about this article?
he best Node.js framework for your project: Express.js, Koa.js or Sails.js is express js the best framework for Node js?

@cmshiyas
Copy link

cmshiyas commented Jun 14, 2017

Awesome! I am new to Node.js and was trying to figure out how to configure this...This worked with a minor update as givne in another post creationix/howtonode.org#88
Thank you very much!

@robole
Copy link

robole commented Jun 26, 2017

ty. min req, what i was after

@dkebler
Copy link

dkebler commented Oct 31, 2017

path.exists has been deprecated. If you want a sync check then

  if (!fs.statSync(filename)) {
    response.writeHead(404, {'Content-Type': 'text/plain'})
    response.write('404 Not Found\n')
    response.end()
    return
  }

@dkebler
Copy link

dkebler commented Oct 31, 2017

even better how about the handler's fs stuff all async with callbacks

fs.stat(filename, function(err,stats) {
    if (err) {
      response.writeHead(404, {'Content-Type': 'text/plain'})
      response.write('404 Not Found\n')
      response.end()
      return
    }

    if (stats.isDirectory()) filename += '/index.html'

    fs.readFile(filename, 'binary', function(err, file) {
      if(err) {
        response.writeHead(500, {'Content-Type': 'text/plain'})
        response.write(err + '\n')
        response.end()
        return
      }
      response.writeHead(200)
      response.write(file, 'binary')
      response.end()
    })
  })

@Risyandi
Copy link

Risyandi commented Apr 19, 2018

Thanks a lot :)

@mandaputtra
Copy link

mandaputtra commented May 6, 2018

Thanks a lot, but it can be hijacked

@XMB5
Copy link

XMB5 commented Jun 10, 2018

This is insecure, someone can request /../../../etc/shadow or similar to read any file they want.

@Abd-Elrazek
Copy link

Abd-Elrazek commented Jul 28, 2019

thanks ...it's great, that why I'm looking for it

@CCorb
Copy link

CCorb commented Feb 29, 2020

path.exists is now called fs.exists

@unsaved
Copy link

unsaved commented Mar 19, 2020

This is insecure, someone can request /../../../etc/shadow or similar to read any file they want.

I guess you're not familiar with how path.join works, because as coded here it won't resolve to a directory outside of cwd directory branch.

@rpivo
Copy link

rpivo commented Apr 12, 2021

fs.exists is deprecated. fs.statSync can be used to check if file path exists, as in dkebler's code above.

@codespede
Copy link

codespede commented May 23, 2021

Thank you for this!

@Anna-art125
Copy link

Anna-art125 commented Jan 25, 2022

Incredible article, thanks for sharing it! I think this article will also be useful for you - Node js vs Python.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment