Click here to Skip to main content
15,886,067 members
Articles / Web Development / Node.js

Node.Js And Stuff

Rate me:
Please Sign up or sign in to vote.
4.97/5 (55 votes)
11 Feb 2013CPOL23 min read 357.3K   2.3K   172  
Small demo app using Node.Js/Socket.IO/MongoDB/D3.Js and jQuery.
{
  "name": "node-static",
  "description": "simple, compliant file streaming module for node",
  "url": "http://github.com/cloudhead/node-static",
  "keywords": [
    "http",
    "static",
    "file",
    "server"
  ],
  "author": {
    "name": "Alexis Sellier",
    "email": "self@cloudhead.net"
  },
  "contributors": [
    {
      "name": "Pablo Cantero",
      "email": "pablo@pablocantero.com"
    }
  ],
  "repository": {
    "type": "git",
    "url": "http://github.com/cloudhead/node-static"
  },
  "main": "./lib/node-static",
  "scripts": {
    "test": "vows --spec --isolate"
  },
  "bin": {
    "static": "bin/cli.js"
  },
  "license": "MIT",
  "dependencies": {
    "optimist": ">=0.3.4",
    "colors": ">=0.6.0"
  },
  "devDependencies": {
    "request": "latest",
    "vows": "latest"
  },
  "version": "0.6.2",
  "engines": {
    "node": ">= 0.4.1"
  },
  "readme": "node-static\n===========\n\n> a simple, *rfc 2616 compliant* file streaming module for [node](http://nodejs.org)\n\nnode-static has an in-memory file cache, making it highly efficient.\nnode-static understands and supports *conditional GET* and *HEAD* requests.\nnode-static was inspired by some of the other static-file serving modules out there,\nsuch as node-paperboy and antinode.\n\nSynopsis\n--------\n\n    var static = require('node-static');\n\n    //\n    // Create a node-static server instance to serve the './public' folder\n    //\n    var file = new(static.Server)('./public');\n\n    require('http').createServer(function (request, response) {\n        request.addListener('end', function () {\n            //\n            // Serve files!\n            //\n            file.serve(request, response);\n        });\n    }).listen(8080);\n\nAPI\n---\n\n### Creating a node-static Server #\n\nCreating a file server instance is as simple as:\n\n    new static.Server();\n\nThis will serve files in the current directory. If you want to serve files in a specific\ndirectory, pass it as the first argument:\n\n    new static.Server('./public');\n\nYou can also specify how long the client is supposed to cache the files node-static serves:\n\n    new static.Server('./public', { cache: 3600 });\n\nThis will set the `Cache-Control` header, telling clients to cache the file for an hour.\nThis is the default setting.\n\n### Serving files under a directory #\n\nTo serve files under a directory, simply call the `serve` method on a `Server` instance, passing it\nthe HTTP request and response object:\n\n    var fileServer = new static.Server('./public');\n\n    require('http').createServer(function (request, response) {\n        request.addListener('end', function () {\n            fileServer.serve(request, response);\n        });\n    }).listen(8080);\n\n### Serving specific files #\n\nIf you want to serve a specific file, like an error page for example, use the `serveFile` method:\n\n    fileServer.serveFile('/error.html', 500, {}, request, response);\n\nThis will serve the `error.html` file, from under the file root directory, with a `500` status code.\nFor example, you could serve an error page, when the initial request wasn't found:\n\n    require('http').createServer(function (request, response) {\n        request.addListener('end', function () {\n            fileServer.serve(request, response, function (e, res) {\n                if (e && (e.status === 404)) { // If the file wasn't found\n                    fileServer.serveFile('/not-found.html', 404, {}, request, response);\n                }\n            });\n        });\n    }).listen(8080);\n\nMore on intercepting errors bellow.\n\n### Intercepting errors & Listening #\n\nAn optional callback can be passed as last argument, it will be called every time a file\nhas been served successfully, or if there was an error serving the file:\n\n    var fileServer = new static.Server('./public');\n\n    require('http').createServer(function (request, response) {\n        request.addListener('end', function () {\n            fileServer.serve(request, response, function (err, result) {\n                if (err) { // There was an error serving the file\n                    sys.error(\"Error serving \" + request.url + \" - \" + err.message);\n\n                    // Respond to the client\n                    response.writeHead(err.status, err.headers);\n                    response.end();\n                }\n            });\n        });\n    }).listen(8080);\n\nNote that if you pass a callback, and there is an error serving the file, node-static\n*will not* respond to the client. This gives you the opportunity to re-route the request,\nor handle it differently.\n\nFor example, you may want to interpret a request as a static request, but if the file isn't found,\nsend it to an application.\n\nIf you only want to *listen* for errors, you can use *event listeners*:\n\n    fileServer.serve(request, response).addListener('error', function (err) {\n        sys.error(\"Error serving \" + request.url + \" - \" + err.message);\n    });\n\nWith this method, you don't have to explicitly send the response back, in case of an error.\n\n### Options when creating an instance of `Server` #\n\n#### `cache` #\n\nSets the `Cache-Control` header.\n\nexample: `{ cache: 7200 }`\n\nPassing a number will set the cache duration to that number of seconds.\nPassing `false` will disable the `Cache-Control` header.\n\n> Defaults to `3600`\n\n\n#### `serverInfo` #\n\nSets the `Server` header.\n\nexample: `{ serverInfo: \"myserver\" }`\n\n> Defaults to `node-static/{version}`\n\n#### `headers` #\n\nSets response headers.\n\nexample: `{ 'X-Hello': 'World!' }`\n\n> defaults to `{}`\n\nCommand Line Interface\n----------------------\n\n`node-static` also provides a CLI.\n\n### Installation #\n\n    $ npm install -g node-static\n\n### Example Usage #\n\n    # serve up the current directory\n    $ static\n    serving \".\" at http://127.0.0.1:8080\n\n    # serve up a different directory\n    $ static public\n    serving \"public\" at http://127.0.0.1:8080\n\n    # specify additional headers (this one is useful for development)\n    $ static -H '{\"Cache-Control\": \"no-cache, must-revaliate\"}'\n    serving \".\" at http://127.0.0.1:8080\n\n    # set cache control max age\n    $ static -c 7200\n    serving \".\" at http://127.0.0.1:8080\n\n    # show help message, including all options\n    $ static -h\n",
  "_id": "node-static@0.6.2",
  "_from": "node-static"
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United Kingdom United Kingdom
I currently hold the following qualifications (amongst others, I also studied Music Technology and Electronics, for my sins)

- MSc (Passed with distinctions), in Information Technology for E-Commerce
- BSc Hons (1st class) in Computer Science & Artificial Intelligence

Both of these at Sussex University UK.

Award(s)

I am lucky enough to have won a few awards for Zany Crazy code articles over the years

  • Microsoft C# MVP 2016
  • Codeproject MVP 2016
  • Microsoft C# MVP 2015
  • Codeproject MVP 2015
  • Microsoft C# MVP 2014
  • Codeproject MVP 2014
  • Microsoft C# MVP 2013
  • Codeproject MVP 2013
  • Microsoft C# MVP 2012
  • Codeproject MVP 2012
  • Microsoft C# MVP 2011
  • Codeproject MVP 2011
  • Microsoft C# MVP 2010
  • Codeproject MVP 2010
  • Microsoft C# MVP 2009
  • Codeproject MVP 2009
  • Microsoft C# MVP 2008
  • Codeproject MVP 2008
  • And numerous codeproject awards which you can see over at my blog

Comments and Discussions