Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 1,000,000+ packages pre-installed, including electricfence with all npm packages installed. Try it out:

var electricfence = require("electricfence")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

electricfence v2.0.1

HAPI plugin to serve files from a directory w/ explicit routes

electric fence

Greenkeeper badge

This is a small hapi module to allow you to serve files and directories from a local path mapped to a url.

How to use

Simply give it a local path and a remote base url

var ElectricFence = require('electricfence');
var Hapi = require('hapi');
var server = new Hapi.server(80);

var options = {
    path: 'public',
    url: '/',
    listing: true,
    index: false,
    cache: 3600000

server.pack.register([{plugin: ElectricFence: options: options}]);

Those are the defaults, so if you pass no options those will be used.

  • path (string, optional, default public): folder to serve files from
  • url (string, optional, default /): url to serve files at
  • listing (boolean, default true): determines if 'index.html' will be served if found in the folder when - requesting a directory
  • index (boolean, default false): determines if directory listing is generated when a directory is requested without an index document
  • cache (integer, default 3600000 (one hour)): time in milliseconds to tell the browser to cache results. Set to 0 to disable browser caching headers
  • labels (string or array, will be passed to see Hapi API docs for more information.


"But Gar," you say, "hapi already has directory and file handlers!"

Yes, but if your server already has a catchall route such as:

    method: 'get',
    path: '/{posts*}',
    handler: postHandler

You can't then add

    method: 'get',
    path: '/{path*}',
    handler: {directory: {path: 'public'}}

The paths will conflict. What electricfence allows you to do is just this.

How it works

electricfence adds explicit file and directory handlers for anything that's in the local path you give it. This means for example if you have a js and css directory in ./public, and you also have a robots.txt file, electricfence will add these handlers

    method: 'get',
    path: '/css/{path*}',
    handler: {directory: {path: 'public/css'}}

    method: 'get',
    path: '/js/{path*}',
    handler: {directory: {path: 'public/js'}}

    method: 'get',
    path: '/robots.txt',
    handler: {file: {path: 'public/robots.txt'}}
RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free