johnnys-node-static

0.1.3 • Public • Published

johnnys-node-static

Simplified version of node-static module.

Documentation

Function Description Example
setStaticServer Sets the static server.
setRoutes Sets the routes object.
exists Verifies if the route does exist and returns true or false.
serve Serves the file specified in routes object.
serveAll Serves any file from root.

Example

File structure:

root/
├── index.js
└── public/
    └── html/
        ├── index.html
        ├── test1.html
        └── test2.html

For the file structure above, the following routes would serve files for each url:

{
    "/":       { "url": "/html/index.html" },
    "/test1/": { "url": "/html/test1.html" },
    "/test2/": { "url": "/html/test2.html" }
}

This is the content for index.js file.

// require Johnny's static
var JohnnysStatic = require("johnnys-node-static"),
    http = require('http');
 
// set static server: public folder
JohnnysStatic.setStaticServer({root: "./public"});
 
// set routes
JohnnysStatic.setRoutes({
    "/":       { "url": "/html/index.html" },
    "/test1/": { "url": "/html/test1.html" },
    "/test2/": { "url": "/html/test2.html" }
});
 
// create http server
http.createServer(function(req, res) {
    // safe serve
    if (JohnnysStatic.exists(req, res)) {
        // serve file
        JohnnysStatic.serve(req, res, function (err) {
            // not found error
            if (err.code === "ENOENT") {
                res.end("404 - Not found.");
                return;
            }
 
            // other error
            res.end(JSON.stringify(err));
        });
        return;
    }
 
    // if the route doesn't exist, it's a 404!
    res.end("404 - Not found");
}).listen(8000);

Test

npm install johnnys-node-static
npm test # or ./test.sh

Changelog

v0.1.3

  • Fixed route setting.

v0.1.2

  • Fixed the bug related to the status code.

v0.1.1

  • Added serveAll method.

v0.1.0

  • Initial release.

Licence

See LICENCE file.

Package Sidebar

Install

npm i johnnys-node-static

Weekly Downloads

1

Version

0.1.3

License

MIT

Last publish

Collaborators

  • ionicabizau