861

Is there Node.js ready-to-use tool (installed with npm), that would help me expose folder content as file server over HTTP.

Example, if I have

D:\Folder\file.zip
D:\Folder\file2.html
D:\Folder\folder\file-in-folder.jpg

Then starting in D:\Folder\ node node-file-server.js I could access file via

http://hostname/file.zip
http://hostname/file2.html
http://hostname/folder/file-in-folder.jpg

Why is my node static file server dropping requests? reference some mystical

standard node.js static file server

If there's no such tool, what framework should I use?

Related: Basic static file server in NodeJS

4

33 Answers 33

1379

A good ready-to-use tool option could be http-server:

npx http-server -o /path/to/static/content

Being a NPM package, can also installed

npm install http-server -g
http-server -o /path/to/static/content
13
  • 11
    This is awesome. I needed to specify an address bc for some reason the default 0.0.0.0 wasn't cooperating w my dev environment. http-server -a localhost got er dun.
    – Sam Berry
    Commented May 15, 2015 at 1:55
  • 53
    i use http-server -a localhost -p 80 Commented Jul 13, 2015 at 19:24
  • 12
    It's worth checking browser-sync too, which can do more-or-less the same thing but with the added bonus of live-updating when files are modified.
    – Nick F
    Commented Oct 14, 2016 at 23:31
  • 5
    --cors to send Access-Control-Allow-Origin:* along with the response headers (ie when serving a json file)
    – Daniel F
    Commented Jun 24, 2017 at 14:28
  • 30
    npx http-server - npx turns it into a one-liner that downloads the necessary files and runs it.
    – Mike McKay
    Commented Nov 13, 2018 at 18:19
261

If you do not want to use ready tool, you can use the code below, as demonstrated by me at https://developer.mozilla.org/en-US/docs/Node_server_without_framework:

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

http.createServer(function (request, response) {
    console.log('request starting...');

    var filePath = '.' + request.url;
    if (filePath == './')
        filePath = './index.html';

    var extname = path.extname(filePath);
    var contentType = 'text/html';
    switch (extname) {
        case '.js':
            contentType = 'text/javascript';
            break;
        case '.css':
            contentType = 'text/css';
            break;
        case '.json':
            contentType = 'application/json';
            break;
        case '.png':
            contentType = 'image/png';
            break;      
        case '.jpg':
            contentType = 'image/jpg';
            break;
        case '.wav':
            contentType = 'audio/wav';
            break;
    }

    fs.readFile(filePath, function(error, content) {
        if (error) {
            if(error.code == 'ENOENT'){
                fs.readFile('./404.html', function(error, content) {
                    response.writeHead(200, { 'Content-Type': contentType });
                    response.end(content, 'utf-8');
                });
            }
            else {
                response.writeHead(500);
                response.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
                response.end(); 
            }
        }
        else {
            response.writeHead(200, { 'Content-Type': contentType });
            response.end(content, 'utf-8');
        }
    });

}).listen(8125);
console.log('Server running at http://127.0.0.1:8125/');

UPDATE If you need to access your server from external demand/file, you need to overcome the CORS, in your node.js file by writing the below, as I mentioned in a previous answer here

// Website you wish to allow to connect
response.setHeader('Access-Control-Allow-Origin', '*');

// Request methods you wish to allow
response.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

// Request headers you wish to allow
response.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
response.setHeader('Access-Control-Allow-Credentials', true);

UPDATE

As Adrian mentioned, in the comments, he wrote an ES6 code with full explanation here, I just re-posting his code below, in case the code gone from the original site for any reason:

const http = require('http');
const url = require('url');
const fs = require('fs');
const path = require('path');
const port = process.argv[2] || 9000;

http.createServer(function (req, res) {
  console.log(`${req.method} ${req.url}`);

  // parse URL
  const parsedUrl = url.parse(req.url);
  // extract URL path
  let pathname = `.${parsedUrl.pathname}`;
  // based on the URL path, extract the file extension. e.g. .js, .doc, ...
  const ext = path.parse(pathname).ext;
  // maps file extension to MIME typere
  const map = {
    '.ico': 'image/x-icon',
    '.html': 'text/html',
    '.js': 'text/javascript',
    '.json': 'application/json',
    '.css': 'text/css',
    '.png': 'image/png',
    '.jpg': 'image/jpeg',
    '.wav': 'audio/wav',
    '.mp3': 'audio/mpeg',
    '.svg': 'image/svg+xml',
    '.pdf': 'application/pdf',
    '.doc': 'application/msword'
  };

  fs.exists(pathname, function (exist) {
    if(!exist) {
      // if the file is not found, return 404
      res.statusCode = 404;
      res.end(`File ${pathname} not found!`);
      return;
    }

    // if is a directory search for index file matching the extension
    if (fs.statSync(pathname).isDirectory()) pathname += '/index' + ext;

    // read file from file system
    fs.readFile(pathname, function(err, data){
      if(err){
        res.statusCode = 500;
        res.end(`Error getting the file: ${err}.`);
      } else {
        // if the file is found, set Content-type and send data
        res.setHeader('Content-type', map[ext] || 'text/plain' );
        res.end(data);
      }
    });
  });


}).listen(parseInt(port));

console.log(`Server listening on port ${port}`);
13
91

For people wanting a server runnable from within NodeJS script:

You can use expressjs/serve-static which replaces connect.static (which is no longer available as of connect 3):

myapp.js:

var http = require('http');

var finalhandler = require('finalhandler');
var serveStatic = require('serve-static');

var serve = serveStatic("./");

var server = http.createServer(function(req, res) {
  var done = finalhandler(req, res);
  serve(req, res, done);
});

server.listen(8000);

and then from command line:

  • $ npm install finalhandler serve-static
  • $ node myapp.js
3
  • 1
    FYI This did not work for me. I installed filehandler using npm install filehandler and the package is listed in the node_modules directory. But when I run myapp.js node throws an error, saying Error: cannot find module filehandler. If I comment out the require ststment to load filehandler the app loads serve-static just fine, so it looks like there's something wrong with the filhandler package. Today is December 12, 2014, so maybe the package has changed since this answer was posted? Commented Dec 12, 2014 at 22:08
  • 10
    It's final handler not file
    – jakub.g
    Commented Dec 12, 2014 at 22:13
  • 1
    another advantage of this solution is, files aren't cached, so you don't need to restart a process when making changes in code.
    – klimat
    Commented Mar 6, 2017 at 12:49
80

I know it's not Node, but I've used Python's SimpleHTTPServer:

python -m SimpleHTTPServer [port]

It works well and comes with Python.

6
  • 30
    Python3 equivalent: python -m http.server [port] (the mentioned one is for Python2)
    – jakub.g
    Commented Mar 19, 2015 at 18:27
  • Python fails for me when it is about serving large files like OS images. Fedora 23
    – Zimy
    Commented Apr 8, 2016 at 11:55
  • 13
    And on PHP: php -S localhost:8000
    – dennis
    Commented Apr 11, 2017 at 17:03
  • I use this to quickly serve content from a folder all the time. Commented May 21, 2017 at 7:11
  • NodeJs equivalent npx http-server [-p 8000] [<dir>]
    – Blaise
    Commented May 5, 2021 at 15:43
59

From [email protected], npm started installing a new binary alongside the usual npm called npx. So now, one liners to create static http server from current directory:

Using https://github.com/vercel/serve

npx serve

or using https://github.com/http-party/http-server

npx http-server
1
37

connect could be what you're looking for.

Installed easily with:

npm install connect

Then the most basic static file server could be written as:

var connect = require('connect'),
    directory = '/path/to/Folder';

connect()
    .use(connect.static(directory))
    .listen(80);

console.log('Listening on port 80.');
2
  • 4
    This does not work any longer as of connect 3 as it doesn't expose connect.static; see my answer below for a replacement
    – jakub.g
    Commented Jul 4, 2014 at 13:17
  • 4
    I believe that it is still bundled with express by default, but indeed exists now in a separate requireable module "serve-static".
    – Oleg
    Commented Jul 4, 2014 at 14:09
33

One-line™ Proofs instead of promises

enter image description here

The first is http-server, hs - link

npm i -g http-server   // install
hs C:\repos            // run with one line?? FTW!!

The second is serve by ZEIT.co - link

npm i -g serve         // install
serve C:\repos         // run with one line?? FTW!!

Following are available options, if this is what helps you decide.

C:\Users\Qwerty>http-server --help
usage: http-server [path] [options]

options:
  -p           Port to use [8080]
  -a           Address to use [0.0.0.0]
  -d           Show directory listings [true]
  -i           Display autoIndex [true]
  -g --gzip    Serve gzip files when possible [false]
  -e --ext     Default file extension if none supplied [none]
  -s --silent  Suppress log messages from output
  --cors[=headers]   Enable CORS via the "Access-Control-Allow-Origin" header
                     Optionally provide CORS headers list separated by commas
  -o [path]    Open browser window after starting the server
  -c           Cache time (max-age) in seconds [3600], e.g. -c10 for 10 seconds.
               To disable caching, use -c-1.
  -U --utc     Use UTC time format in log messages.

  -P --proxy   Fallback proxy if the request cannot be resolved. e.g.: http://someurl.com

  -S --ssl     Enable https.
  -C --cert    Path to ssl cert file (default: cert.pem).
  -K --key     Path to ssl key file (default: key.pem).

  -r --robots  Respond to /robots.txt [User-agent: *\nDisallow: /]
  -h --help    Print this list and exit.
C:\Users\Qwerty>serve --help

  Usage: serve.js [options] [command]

  Commands:

    help  Display help

  Options:

    -a, --auth      Serve behind basic auth
    -c, --cache     Time in milliseconds for caching files in the browser
    -n, --clipless  Don't copy address to clipboard (disabled by default)
    -C, --cors      Setup * CORS headers to allow requests from any origin (disabled by default)
    -h, --help      Output usage information
    -i, --ignore    Files and directories to ignore
    -o, --open      Open local address in browser (disabled by default)
    -p, --port   Port to listen on (defaults to 5000)
    -S, --silent    Don't log anything to the console
    -s, --single    Serve single page applications (sets `-c` to 1 day)
    -t, --treeless  Don't display statics tree (disabled by default)
    -u, --unzipped  Disable GZIP compression
    -v, --version   Output the version number

If you need to watch for changes, see hostr, credit Henry Tseng's answer

0
33

Install express using npm: https://expressjs.com/en/starter/installing.html

Create a file named server.js at the same level of your index.html with this content:

var express = require('express');
var server = express();
server.use(express.static(__dirname));
server.listen(8080);

This will load your index.html file. If you wish to specify the html file to load, use this syntax:

server.use('/', express.static(__dirname + '/myfile.html'));

If you wish to put it in a different location, set the path on the third line:

server.use('/', express.static(__dirname + '/public'));

CD to the folder containing your file and run node from the console with this command:

node server.js

Browse to localhost:8080

3
  • 1
    Hi, I can run it correctly, but it shows Cannot GET /. I use AWS EC2 to run the server.
    – Wei Xia
    Commented Nov 4, 2016 at 18:55
  • 1
    @Wei Hi, late answer. From what I can see from a quick Google search it looks like your directory structure might be wrong. There must be an index.html file in the location you are targeting. Setting up the above example to run should take 5 minutes and I double checked that it works as is. From there you can tweak the path to suit your directory structure and check that the server still finds the files it needs to server.
    – pasx
    Commented Dec 3, 2016 at 14:22
  • path.join(__dirname, 'public') is more cross-platform.
    – sdgfsdh
    Commented Aug 2, 2017 at 20:09
19

#DEMO/PROTO SERVER ONLY

If that's all you need, try this:

const fs = require('fs'),
      http = require('http'),
      arg = process.argv.slice(2),
      rootdir = arg[0] || process.cwd(),
      port = process.env.PORT || 9000,
      hostname = process.env.HOST || '127.0.0.1';
//tested on node=v10.19.0
http.createServer(function (req, res) {

  try {
    // change 'path///to/////dir' -> 'path/to/dir'
    req_url = decodeURIComponent(req.url).replace(/\/+/g, '/');

    stats = fs.statSync(rootdir + req_url);

    if (stats.isFile()) {
      buffer = fs.createReadStream(rootdir + req_url);
      buffer.on('open', () => buffer.pipe(res));
      return;
    }

    if (stats.isDirectory()) {
      //Get list of files and folder in requested directory
      lsof = fs.readdirSync(rootdir + req_url, {encoding:'utf8', withFileTypes:false});
      // make an html page with the list of files and send to browser
      res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
      res.end(html_page(`http://${hostname}:${port}`, req_url, lsof));
      return;
    }

  } catch (err) {
      res.writeHead(404);
      res.end(err);
      return;
  }
}).listen(port, hostname, () => console.log(`Server running at http://${hostname}:${port}`));


function html_page(host, req_url, lsof) {//this is a Function declarations can be called before it is defined
  // Add link to root directory and parent directory if not already in root directory
  list = req_url == '/' ? [] : [`<a href="${host}">/</a>`,
  `<a href="${host}${encodeURI(req_url.slice(0,req_url.lastIndexOf('/')))}">..</a>`];

  templete = (host, req_url, file) => {// the above is a Function expressions cannot be called before it is defined
    return `<a href="${host}${encodeURI(req_url)}${req_url.slice(-1) == '/' ? '' : '/'}${encodeURI(file)}">${file}</a>`; }

  // Add all the links to the files and folder in requested directory
  lsof.forEach(file => {
    list.push(templete(host, req_url, file));
  });

  return `
<!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="content-type" content="text/html" charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Directory of ${req_url}</title>
</head>
<body>
<h2>Directory of ${req_url}</h2>
${list.join('<br/>\n')}
</body>
</html>`
}
4
  • 2
    Don't use the sync version. Instread create pipe to res from readStream. Commented Jun 28, 2017 at 6:46
  • 1
    Best answer if you need a quick & dirty one-time one trick pony.
    – collapsar
    Commented Jul 9, 2018 at 15:30
  • 1
    If you want to avoid using index.html as part of your address just add if (req.url === '/') req.url = '/index.html'; right after res.writeHead(200);.
    – Joseph Cho
    Commented Apr 16, 2019 at 20:44
  • 4
    @EduardBondarenko is right. const stream = fs.createReadStream(...); stream.pipe(res); is all you need Commented May 29, 2019 at 20:53
13

In plain node.js:

const http = require('http')
const fs = require('fs')
const path = require('path')

process.on('uncaughtException', err => console.error('uncaughtException', err))
process.on('unhandledRejection', err => console.error('unhandledRejection', err))

const publicFolder = process.argv.length > 2 ? process.argv[2] : '.'
const port = process.argv.length > 3 ? process.argv[3] : 8080

const mediaTypes = {
  zip: 'application/zip',
  jpg: 'image/jpeg',
  html: 'text/html',
  /* add more media types */
}

const server = http.createServer(function(request, response) {
  console.log(request.method + ' ' + request.url)

  const filepath = path.join(publicFolder, request.url)
  fs.readFile(filepath, function(err, data) {
    if (err) {
      response.statusCode = 404
      return response.end('File not found or you made an invalid request.')
    }

    let mediaType = 'text/html'
    const ext = path.extname(filepath)
    if (ext.length > 0 && mediaTypes.hasOwnProperty(ext.slice(1))) {
      mediaType = mediaTypes[ext.slice(1)]
    }

    response.setHeader('Content-Type', mediaType)
    response.end(data)
  })
})

server.on('clientError', function onClientError(err, socket) {
  console.log('clientError', err)
  socket.end('HTTP/1.1 400 Bad Request\r\n\r\n')
})

server.listen(port, '127.0.0.1', function() {
  console.log('👨‍🔧 Development server is online.')
})

This is a simple node.js server that only serves requested files in a certain directory.

Usage:

node server.js folder port

folder may be absolute or relative depending on the server.js location. The default value is . which is the directory you execute node server.js command.

port is 8080 by default but you can specify any port available in your OS.

In your case, I would do:

cd D:\Folder
node server.js

You can browse the files under D:\Folder from a browser by typing http://127.0.0.1:8080/somefolder/somefile.html

9

There is another static web server that is quite nice: browser-sync.

It can be downloaded using node package manager:

npm install -g browser-sync

After installation, navigate to the project folder in the cmd prompt and just run the following:

browser-sync start --server --port 3001 --files="./*"

It will start catering all the files in the current folder in the browser.

More can be found out from BrowserSync

Thanks.

1
  • 2
    The advantage of using Browsersync rather than other static servers is that it live updates the page whenever the files specified by the --files flag change (nb. you don't need to specify ./* - only the ones that you want Browsersync to actively watch for updates, eg. css/*.css)
    – Nick F
    Commented Oct 14, 2016 at 23:28
9

Here is my one-file/lightweight node.js static file web-server pet project with no-dependency that I believe is a quick and rich tool which its use is as easy as issuing this command on your Linux/Unix/macOS terminal (or termux on Android) when node.js (or nodejs-legacy on Debian/Ubuntu) is installed:

curl pad.js.org | node 

(different commands exist for Windows users on the documentation)

It supports different things that I believe can be found useful,

  • Hierarchical directory index creation/serving
    • With sort capability on the different criteria
    • Upload from browser by [multi-file] drag-and-drop and file/text-only copy-paste and system clipboard screen-shot paste on Chrome, Firefox and other browsers may with some limitations (which can be turned off by command line options it provides)
    • Folder/note-creation/upload button
  • Serving correct MIMEs for well known file types (with possibility for disabling that)
  • Possibility of installation as a npm package and local tool or, one-linear installation as a permanent service with Docker
  • HTTP 206 file serving (multipart file transfer) for faster transfers
  • Uploads from terminal and browser console (in fact it was originally intended to be a file-system proxy for JS console of browsers on other pages/domains)
  • CORS download/uploads (which also can be turned off)
  • Easy HTTPS integration
  • Lightweight command line options for achieving better secure serving with it:
    • With my patch on node.js 8, you can have access to the options without first installation: curl pad.js.org | node - -h
    • Or first install it as a system-global npm package by [sudo] npm install -g pad.js and then use its installed version to have access to its options: pad -h
    • Or use the provided Docker image which uses relatively secure options by default. [sudo] docker run --restart=always -v /files:/files --name pad.js -d -p 9090:9090 quay.io/ebraminio/pad.js

Screenshot of a folder index using the tool

The features described above are mostly documented on the main page of the tool http://pad.js.org which by some nice trick I used is also the place the tool source itself is also served from!

The tool source is on GitHub which welcomes your feedback, feature requests and ⭐s!

0
8

You can use the NPM serve package for this, if you don't need the NodeJS stuff it is a quick and easy to use tool:

1 - Install the package on your PC:

npm install -g serve

2 - Serve your static folder with serve <path> :

d:> serve d:\StaticSite

It will show you which port your static folder is being served, just navigate to the host like:

http://localhost:3000
2
  • You realize that npm is the node package manager so you're in fact using the NodeJS stuff
    – derickito
    Commented Mar 31, 2019 at 21:09
  • 1
    I do, What I meant as "NodeJS stuff" was using NodeJS and express to serve the files like most answers suggested. Serve is an independent executable, NPM is used just to install it, you could just download it directly. Commented Apr 1, 2019 at 9:19
7

I haven't had much luck with any of the answers on this page, however, below seemed to do the trick.

Add a server.js file with the following content:

const express = require('express')
const path = require('path')
const port = process.env.PORT || 3000
const app = express()

// serve static assets normally
app.use(express.static(__dirname + '/dist'))

// handle every other route with index.html, which will contain
// a script tag to your application's JavaScript file(s).
app.get('*', function (request, response){
  response.sendFile(path.resolve(__dirname, 'dist', 'index.html'))
})

app.listen(port)
console.log("server started on port " + port)

Also make sure that you require express. Run yarn add express --save or npm install express --save depending on your setup (I can recommend yarn it's pretty fast).

You may change dist to whatever folder you are serving your content is. For my simple project, I wasn't serving from any folder, so I simply removed the dist filename.

Then you may run node server.js. As I had to upload my project to a Heroku server, I needed to add the following to my package.json file:

  "scripts": {
    "start": "node server.js"
  }
7

Below worked for me:

Create a file app.js with below contents:

// app.js

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

http.createServer(function (req, res) {
  fs.readFile(__dirname + req.url, function (err,data) {
    if (err) {
      res.writeHead(404);
      res.end(JSON.stringify(err));
      return;
    }
    res.writeHead(200);
    res.end(data);
  });
}).listen(8080);

Create a file index.html with below contents:

Hi

Start a command line:

cmd

Run below in cmd:

node app.js

Goto below URL, in chrome:

http://localhost:8080/index.html

That's all. Hope that helps.

Source: https://nodejs.org/en/knowledge/HTTP/servers/how-to-serve-static-files/

4

If you use the Express framework, this functionality comes ready to go.

To setup a simple file serving app just do this:

mkdir yourapp
cd yourapp
npm install express
node_modules/express/bin/express
2
  • Can I $ npm install -g express ; them $ express ? Commented May 2, 2013 at 10:30
  • 1
    I followed your steps, but my express does not have bin folder
    – Qwerty
    Commented Nov 30, 2017 at 10:02
4

Searching in NPM registry https://npmjs.org/search?q=server, I have found static-server https://github.com/maelstrom/static-server

Ever needed to send a colleague a file, but can't be bothered emailing the 100MB beast? Wanted to run a simple example JavaScript application, but had problems with running it through the file:/// protocol? Wanted to share your media directory at a LAN without setting up Samba, or FTP, or anything else requiring you to edit configuration files? Then this file server will make your life that little bit easier.

To install the simple static stuff server, use npm:

npm install -g static-server

Then to serve a file or a directory, simply run

$ serve path/to/stuff
Serving path/to/stuff on port 8001

That could even list folder content.

Unfortunately, it couldn't serve files :)

2
  • 6
    I built that server. That file server was built against a very old version of Node, hence why it does not work any more. I do not have the time right now to fix it up. I suggest using the answer by @Oleg above. It can be easily bundled into a small node executable, and is essentially what mine did anyway.
    – Tim Heap
    Commented May 2, 2013 at 11:05
  • Thank you Tim, very professional response. I wouldn't delete code though, but update readme. Commented May 2, 2013 at 14:05
4

You can try serve-me

Using it is so easy:

ServeMe = require('serve-me')();
ServeMe.start(3000);

Thats all.

PD: The folder served by default is "public".

4

Here's another simple web server.

https://www.npmjs.com/package/hostr

Install

npm install -g hostr

Change working director

cd myprojectfolder/

And start

hostr
1
  • This also watches for changes and provides live reload.
    – Qwerty
    Commented Nov 30, 2017 at 10:55
4

For a healthy increase of performance using node to serve static resources, I recommend using Buffet. It works similar to as a web application accelerator also known as a caching HTTP reverse proxy but it just loads the chosen directory into memory.

Buffet takes a fully-bufferred approach -- all files are fully loaded into memory when your app boots, so you will never feel the burn of the filesystem. In practice, this is immensely efficient. So much so that putting Varnish in front of your app might even make it slower! 

We use it on the codePile site and found an increase of ~700requests/sec to >4k requests/sec on a page that downloads 25 resources under a 1k concurrent user connection load.

Example:

var server = require('http').createServer();

var buffet = require('buffet')(root: './file'); 

 

server.on('request', function (req, res) {

  buffet(req, res, function () {

    buffet.notFound(req, res);

  });

});

 

server.listen(3000, function () {

  console.log('test server running on port 3000');

});
4

Take a look on that link.

You need only to install express module of node js.

var express = require('express');
var app = express();

app.use('/Folder', express.static(__dirname + '/Folder'));

You can access your file like http://hostname/Folder/file.zip

3

First install node-static server via npm install node-static -g -g is to install it global on your system, then navigate to the directory where your files are located, start the server with static it listens on port 8080, naviaget to the browser and type localhost:8080/yourhtmlfilename.

2

A simple Static-Server using connect

var connect = require('connect'),
  directory = __dirname,
  port = 3000;

connect()
  .use(connect.logger('dev'))
  .use(connect.static(directory))
  .listen(port);

console.log('Listening on port ' + port);

See also Using node.js as a simple web server

2

It isn't on NPM, yet, but I built a simple static server on Express that also allows you to accept form submissions and email them through a transactional email service (Sendgrid for now, Mandrill coming).

https://github.com/jdr0dn3y/nodejs-StatServe

2

For the benefit of searchers, I liked Jakub g's answer, but wanted a little error handling. Obviously it's best to handle errors properly, but this should help prevent a site stopping if an error occurs. Code below:

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

process.on('uncaughtException', function(err) {
  console.log(err);
});

var server = express();

server.use(express.static(__dirname));

var port = 10001;
server.listen(port, function() { 
    console.log('listening on port ' + port);     
    //var err = new Error('This error won't break the application...')
    //throw err
});
1
  • Update - My answer works, but I now use @Matt Self's answer of using http-server. It seems to work well. Commented Nov 6, 2015 at 15:27
1

For dev work you can use (express 4) https://github.com/appsmatics/simple-httpserver.git

1

If you want daemon http-server/static-files-server, you may need https://github.com/AJLoveChina/hs3 , which supports running as background task.

npm install -g hs3

Usage

move to the directory which serve static files and run

hs3

Really fast and quick? Yes ! And the file server or static server will be running as background task.

It also supports using another http port, or https. Please click https://github.com/AJLoveChina/hs3 for more details.

0

I use Houston at work and for personal projects, it works well for me.

https://github.com/alejandro/Houston

0

const http = require('http');
const fs = require('fs');
const url = require('url');
const path = require('path');


let mimeTypes = {
  '.html': 'text/html',
  '.css': 'text/css',
  '.js': 'text/javascript',
  '.jpg': 'image/jpeg',
  '.png': 'image/png',
  '.ico': 'image/x-icon',
  '.svg': 'image/svg+xml',
  '.eot': 'appliaction/vnd.ms-fontobject',
  '.ttf': 'aplication/font-sfnt'
};



http.createServer(function (request, response) {
  let pathName = url.parse(request.url).path;
  if(pathName === '/'){
    pathName = '/index.html';
  }
  pathName = pathName.substring(1, pathName.length);
  let extName = path.extName(pathName);
  let staticFiles = `${__dirname}/template/${pathName}`;

      if(extName =='.jpg' || extName == '.png' || extName == '.ico' || extName == '.eot' || extName == '.ttf' || extName == '.svg')
      {
          let file = fr.readFileSync(staticFiles);
          res.writeHead(200, {'Content-Type': mimeTypes[extname]});
          res.write(file, 'binary');
          res.end();
      }else {
        fs.readFile(staticFiles, 'utf8', function (err, data) {
          if(!err){
            res.writeHead(200, {'Content-Type': mimeTypes[extname]});
            res.end(data);
          }else {
            res.writeHead(404, {'Content-Type': 'text/html;charset=utf8'});
            res.write(`<strong>${staticFiles}</strong>File is not found.`);
          }
          res.end();
        });
      }
}).listen(8081);

2
  • You should add some explanation alog with this code. Commented Feb 23, 2016 at 13:51
  • Lot's of error in this. Variable names are not consistend (response, res etc).
    – Paflow
    Commented Jun 13, 2022 at 7:32
0

If you are intrested in ultra-light http server without any prerequisites you should have a look at: mongoose

1
  • This is a C++ Server which has no relation to a Node.js Solution. Also the name is misleading in this Thread because it shares it's name with a popular MongoDB Layer for Node.js.
    – cgn.dev
    Commented Dec 1, 2020 at 15:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.