Git Product home page Git Product logo

node-static's Introduction

node-static

Node.js CI status

a simple, rfc 2616 compliant file streaming module for node

node-static understands and supports conditional GET and HEAD requests. node-static was inspired by some of the other static-file serving modules out there, such as node-paperboy and antinode.

Installation

$ npm install node-static

Set-up

ESM

import {Server, version, mime} from 'node-static';

// OR:
// import * as statik from 'node-static';

CommonJS

const statik = require('node-static');

Usage

//
// Create a node-static server instance to serve the './public' folder
//
const file = new statik.Server('./public');

require('http').createServer(function (request, response) {
    request.addListener('end', function () {
        //
        // Serve files!
        //
        file.serve(request, response);
    }).resume();
}).listen(8080);

API

Creating a node-static Server

Creating a file server instance is as simple as:

new statik.Server();

This will serve files in the current directory. If you want to serve files in a specific directory, pass it as the first argument:

new statik.Server('./public');

You can also specify how long the client is supposed to cache the files node-static serves:

new statik.Server('./public', { cache: 3600 });

This will set the Cache-Control header, telling clients to cache the file for an hour. This is the default setting.

Serving files under a directory

To serve files under a directory, simply call the serve method on a Server instance, passing it the HTTP request and response object:

const statik = require('node-static');

var fileServer = new statik.Server('./public');

require('http').createServer(function (request, response) {
    request.addListener('end', function () {
        fileServer.serve(request, response);
    }).resume();
}).listen(8080);

Serving specific files

If you want to serve a specific file, like an error page for example, use the serveFile method:

fileServer.serveFile('/error.html', 500, {}, request, response);

This will serve the error.html file, from under the file root directory, with a 500 status code. For example, you could serve an error page, when the initial request wasn't found:

require('http').createServer(function (request, response) {
    request.addListener('end', function () {
        fileServer.serve(request, response, function (e, res) {
            if (e && (e.status === 404)) { // If the file wasn't found
                fileServer.serveFile(
                    '/not-found.html', 404, {}, request, response
                );
            }
        });
    }).resume();
}).listen(8080);

More on intercepting errors bellow.

Intercepting errors & Listening

An optional callback can be passed as last argument, it will be called every time a file has been served successfully, or if there was an error serving the file:

const statik = require('node-static');

const fileServer = new statik.Server('./public');

require('http').createServer(function (request, response) {
    request.addListener('end', function () {
        fileServer.serve(request, response, function (err, result) {
            if (err) { // There was an error serving the file
                console.error(
                    "Error serving " + request.url + " - " + err.message
                );

                // Respond to the client
                response.writeHead(err.status, err.headers);
                response.end();
            }
        });
    }).resume();
}).listen(8080);

Note that if you pass a callback, and there is an error serving the file, node-static will not respond to the client. This gives you the opportunity to re-route the request, or handle it differently.

For example, you may want to interpret a request as a static request, but if the file isn't found, send it to an application.

If you only want to listen for errors, you can use event listeners:

fileServer.serve(request, response).addListener('error', function (err) {
    console.error("Error serving " + request.url + " - " + err.message);
});

With this method, you don't have to explicitly send the response back, in case of an error.

Options when creating an instance of Server

cache (Default: 3600)

Sets the Cache-Control header.

example: { cache: 7200 } will set the max-age for all files to 7200 seconds example: { cache: {'**/*.css': 300}} will set the max-age for all CSS files to 5 minutes.

Passing a number will set the cache duration to that number of seconds. Passing false will disable the Cache-Control header. Passing a object with minimatch glob pattern keys and number values will set cache max-age for any matching paths.

serverInfo (Default: node-static/{version})

Sets the Server header.

example: { serverInfo: "myserver" }

headers (Default: {})

Sets response headers.

example: { headers: { 'X-Hello': 'World!' } }

gzip (Default: false)

Enable support for sending compressed responses. This will enable a check for a file with the same name plus '.gz' in the same folder. If the compressed file is found and the client has indicated support for gzip file transfer, the contents of the .gz file will be sent in place of the uncompressed file along with a Content-Encoding: gzip header to inform the client the data has been compressed.

example: { gzip: true } example: { gzip: /^\/text/ }

Passing true will enable this check for all files. Passing a RegExp instance will only enable this check if the content-type of the respond would match that RegExp using its test() method.

indexFile (Default: index.html)

Choose a custom index file when serving up directories.

example: { indexFile: "index.htm" }

defaultExtension (Default: null)

Choose a default extension when serving files. A request to '/myFile' would check for a myFile folder (first) then a myFile.html (second).

example: { defaultExtension: "html" }

Command Line Interface

node-static also provides a CLI.

--port, -p          TCP port at which the files will be served                        [default: 8080]
--host-address, -a  the local network interface at which to listen                    [default: "127.0.0.1"]
--cache, -c         "Cache-Control" header setting, defaults to 3600
--version, -v       node-static version
--headers, -H       additional headers (in JSON format)
--header-file, -f   JSON file of additional headers
--gzip, -z          enable compression (tries to serve file of same name plus '.gz')
--spa               Serve the content as a single page app by redirecting all
                    non-file requests to the index HTML file.
--indexFile, -i     Specify a custom index file when serving up directories.          [default: "index.html"]
--help, -h          display this help message

Example Usage

# serve up the current directory
$ static
serving "." at http://127.0.0.1:8080

# serve up a different directory
$ static public
serving "public" at http://127.0.0.1:8080

# specify additional headers (this one is useful for development)
$ static -H '{"Cache-Control": "no-cache, must-revalidate"}'
serving "." at http://127.0.0.1:8080

# set cache control max age
$ static -c 7200
serving "." at http://127.0.0.1:8080

# expose the server to your local network
$ static -a 0.0.0.0
serving "." at http://0.0.0.0:8080

# show help message, including all options
$ static -h

node-static's People

Contributors

aaronj1335 avatar brapse avatar brettz9 avatar cimnine avatar cloudhead avatar dobesv avatar dpp-name avatar dubiousdavid avatar ef4 avatar endangeredmassa avatar guybedford avatar hayashi311 avatar ionicabizau avatar jeremybarnes avatar joshlangner avatar kapouer avatar m64253 avatar mmcdermott avatar pbouzakis avatar phstc avatar pixcai avatar rsolomo avatar sebs avatar sideshowbarker avatar tchakabam avatar teeteehaa avatar thbaja avatar valentinvieriu avatar yinglei avatar zhangyijun avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-static's Issues

node-static.js uses 'this' instead of 'exports'

node-static.js is using this to apply exports to instead of exports. Although this works in node due to the way it loads modules, this is outside of the spec of commonjs.

node-static.js should be using the exports property instead.

I'll submit a pull request shortly.

node-static not working with node 0.10.3

Since I updated node, node-static is not working anymore.
The server startup normally but I don't get any file served on the browser. I've rolled back to another version of node and it's working normally.
Do you have any idea why?
Thanx.

Cannot call method 'toString' of null

http:572
  var statusLine = "HTTP/1.1 " + statusCode.toString() + " "

TypeError: Cannot call method 'toString' of null

For string 215
if (e) { return finish(null, {}) }

Maybe 404 instead null?

Traceback with node-static 0.5.9 (socket is not writable)

I was able to trigger that, but don't ask me how:

net.js:391
    throw new Error('Socket is not writable');
          ^
Error: Socket is not writable
    at Socket._writeOut (net.js:391:11)
    at Socket.write (net.js:377:17)
    at ServerResponse._writeRaw (http.js:391:28)
    at ServerResponse._send (http.js:371:15)
    at ServerResponse.write (http.js:621:16)
    at ServerResponse.end (http.js:681:16)
    at [object Object].respond (/node_modules/node-static/lib/node-static.js:211:17)
    at /node_modules/node-static/lib/node-static.js:142:22

Cannot find module 'node-static'

Hi All,

I am new Node.js. I installed recent version node.js. My problem is when i create static server it throws Cannot find module 'node-static'. I try to install node-static by using the command "npm install -g node-static". It install the npm node-static in the C:\Users\AppData\Roaming\npm\node_modules\node-static.
when the run the node.js agani it throws Cannot find module 'node-static'

Thakns in Advance

When 'Content-Type' header is provided to serve, do not detect it based on file extension.

I am saving files on disk without extension (I have a DB that manages file names and extensions and the files on disk are only IDs).

With node static you can specify headers (for me Content-Type is important) using either the static server configuration upon creation or by using the serveFile function.

Specifying the header as a server configuration is not an option because there is not a single type of files.

I also tried serveFile:

fileServer.serveFile(filePath, 200, { 'Content-Type: ': file_content_type }, req, res);  

but because the file has no extension what I get in the browser is (example for an image):

Content-Type:: image/png
Content-Type:application/octet-stream

Therefore, node-static, should overwrite user specified headers.

Remove "request.addListener('end'"

I noticed that when using my default node-static stub file, based on the example from the README.md, the node server would run and register receiving the HTTP request, but never serve the data. It appears that the addListener statement is no longer required.

Here's the block form the README.md

require('http').createServer(function (request, response) {
request.addListener('end', function () {
//
// Serve files!
//
file.serve(request, response);
}).resume();
}).listen(8080);

This is a working solution:

// Create HTTP server
var serv = http.createServer(function (req, res) {
console.log('HTTP Connection');
file.serve(req, res);
}).listen(8081);

Invalid dependencies format in package.json

Hi,

in package.json, "dependencies" is an array (empty). This is not a correct format according to the package.json specification:

http://wiki.commonjs.org/wiki/Packages/1.1#Package_Descriptor_File
or
http://package.json.nodejitsu.com/

This causes an npm install to throw a warning if called from a package that that already has node-static installed in its node_modules.

npm WARN [email protected] dependencies field should be hash of <name>:<version-range> pairs

update README file

in section "Serving specific files" the README uses serveFiles without status code or headers object. this causes the error described in issue #25.

"Can't render headers after they are sent to the client" for GET / requests

I started to get this error after some changes in my code (not sure what changes).
This error only triggers upon GET request to "/" path. GETting "/index.html" doesn't trigger it.

http.js:571

    throw new Error("Can't render headers after they are sent to the client.")


     ^

G: Error: Can't render headers after they are sent to the client.
at ServerResponse._renderHeaders (http.js:571:11)
at ServerResponse.writeHead (http.js:804:20)
at [object Object].respond (/usr/local/lib/node/.npm/node-static/0.5.3/package/lib/node-static.js:205:13)
at /usr/local/lib/node/.npm/node-static/0.5.3/package/lib/node-static.js:55:18

In my code, this is where I'm serving files:

if ((typeof params !== 'undefined') && (typeof params.route !== 'undefined')){
    if (params.route === '/'){
        file.serveFile('/index.html', 200, {}, request, response);
    }

    if (params.route === '/123'){
        file.serveFile('/index.html', 200, {}, request, response);
    }
}

Here params.route === '/' triggers the error while params.route === '/123' doesn't.
I don't write response anywhere before this code.

Cleanup Issues List

I've reviewed the code for this project and it's well written and clean. However, the number of pull requests/issues makes this project seem a little untrustworthy in my opinion. Can you clean up the issues list and provide some direction as far as the future goals of the project. I'm happy to help in any capacity :)

node-static-test.js fails test "requesting HEAD"

node-static of May 20 up to commit e294621
node 0.8.22
Windows 7 64 Bit
had to install vows: npm install vows
had to install request: npm install request

node node-static-test.js fails test "requesting HEAD" because body is an empty string:

· ·· · · · ··· ·· ·· ·· ·? · ·

    requesting HEAD
      ? head must has no body
        » expected '' to be undefined // node-static-test.js:186
  ? Broken » 18 honored  1 broken (0.296s)

FATAL ERROR: CALL_AND_RETRY_2 Allocation failed - process out of memory

I get the following error message when serving big files:
at Socket.EventEmitter.once (events.js:179:8)
at TCP.onread (net.js:527:26)
FATAL ERROR: CALL_AND_RETRY_2 Allocation failed - process out of memory
(node) warning: possible EventEmitter memory leak detected. 11 listeners added. Use emitter.setMaxListeners() to increase limit.
Trace
at Socket.EventEmitter.addListener (events.js:160:15)
at Socket.Readable.on (_stream_readable.js:679:33)
at Socket.EventEmitter.once (events.js:179:8)
at TCP.onread (net.js:527:26)
FATAL ERROR: CALL_AND_RETRY_2 Allocation failed - process out of memory

My Code is:
var static = require('node-static');

//
// Create a node-static server instance to serve the './public' folder
//
var file = new(static.Server)('./../content',{ headers: {
'Content-Description':'File Transfer',
'Content-Type':'video/mp4',
'Content-Transfer-Encoding':'binary',
'Content-Disposition':'attachment; filename=recording.mp4'
}});

require('http').createServer(function (request, response) {
request.addListener('end', function () {
//
// Serve files!
//
file.serve(request, response);
}).resume();
}).listen(8080);

Any idea?

Gzip support

Seems given the current implementation there is no way to put in a simple handler for gzip compression. This would be quite useful for speeding up some files being served.

I'm not saying put a full middleware stack in there for your static files, but just a single flag "gzip", which can optionally gzip files that match a given regexp.

Thoughts?

node-static win32 forbiden

using node + node-static on winxp and setting
var fileServer = new nstatic.Server("C:/public");
gave me an error everytime i tried to acces the localhost:8080 expecting to load the index.html

error comes from this line in node-static.js

this.Server.prototype.servePath = function (pathname, status, headers, req, res, finish)
......
// Make sure we're not trying to access a file outside of the root.
if (new(RegExp)('^' + that.root).test(pathname)) {

in that regex, pathname was C:\public and that.root = C:\public too.

so while in development (i dont have to worry bout someone trying to acces another files)
i comented this line and now is working fine

sorry for my english

Cannot call 'copy' method of string

It seems like node may have an update such that the 'data' event of a ReadableStream returns string chunks and not buffers. This causes the following exception:

/usr/local/lib/node/.npm/node-static/0.5.1/package/lib/node-static.js:239
                chunk.copy (buffer, offset, 0);

has no method 'copy'
    at [object Object]. (/usr/local/lib/node/.npm/node-static/0.5.1/package/lib/node-static.js:239:23)
    at [object Object].emit (events:27:15)
    at [object Object]._emitData (fs:752:29)
    at afterRead (fs:733:10)
    at node.js:599:9

This is simple to fix. Simply replace the line in question: http://github.com/cloudhead/node-static/blob/master/lib/node-static.js#L239 with this:

buffer.write(chunk, offset, 'binary');

missing trailing slash in URL when using default file "index.html"

This issue is for node-static version 0.5.9.

In case the URL does not contain a file node-static tries to serve the default file "index.html". In case the file exists it does not matter whether the URL contains a trailing slash or not:

http://localhost/path/ ==> serves index.html
http://localhost/path ==> serves index.html

But if the file (index.html) includes some other files, e.x. a JS script file (code.js), the loading of the JS script file will fail with an "404 Not Found" error because the browser is assuming a wrong path for the JS script file:

http://localhost/path/ ==> serves index.html and serves code.js
http://localhost/path ==> serves index.html and serves 404 for code.js

The same examples in Apache look like this:

http://localhost/path/ ==> serves index.html and serves code.js
http://localhost/path ==> serves "301 Moved Permanently" with a header "Location" containing the URL including the trailing slash where the browser then goes to

I've written a proof-of-concept to demonstrate this bug:

https://gist.github.com/2983697

npm install fails for shared virtual machines

Hey, I use VBox and I share a common folder between linux guest and the host OS. And a lot of modules love to use symlinks - which are great and all, but they break on shared folders.

I don't actually use the bin/cli.js so it would be nice if this showed as a WARNING rather than threw an error and causing everything else to fail. Thanks!

npm ERR! Error: EROFS, symlink '../node-static/bin/cli.js'
npm ERR! If you need help, you may report this log at:
npm ERR!     <http://github.com/isaacs/npm/issues>
npm ERR! or email it to:
npm ERR!     <[email protected]>

npm ERR! System Linux 3.2.0-29-generic
npm ERR! command "/usr/local/bin/node" "/usr/local/bin/npm" "install" "coalesce"
npm ERR! node -v v0.8.15
npm ERR! npm -v 1.1.66
npm ERR! path ../node-static/bin/cli.js
npm ERR! code EROFS
npm ERR! errno 56
npm ERR! 
npm ERR! not ok code 0

file length truncated

I'm trying to build an app that serves the same page no matter what url is called (except when loading assets). strangely, it load the html file correctly the first time, but it truncates the file on the consequent loads, thus breaking the HTML code.
here's my code:
https://gist.github.com/3728a339257fd70acc19

is there any additional setting needed?

Files stored in cache even if cache is disabled

There's a piece of code:

        this.stream(pathname, files, new(buffer.Buffer)(stat.size), res, function (e, buffer) {
            if (e) { return finish(500, {}) }
            exports.store[key] = {
                stat:      stat,
                buffer:    buffer,
                timestamp: Date.now()
            };
            finish(status, headers);
        });

It should have an if(that.cache) in there to check if the cache is enabled, otherwise the data stored in the cache will never be retrieved and it's just wasting memory. If someone had a lot of static files they would not be happy about all that wasted memory!

Of course as someone pointed out in another ticket, there's a case to be made for eliminating the in-memory cache altogether as reading static files as the OS generally does this caching for you. Caches are more useful for dynamically generated data. Eliminating the in-memory cache would also fix this issue.

https

Though it might be impractical to serve static files via https://, wonder why node-static refuses to serve some files in secure mode (no error, just response content is missing), while being an excellent unsecured server?

TIA,
--Vladimir

default parameters for .respond()

node_modules/node-static/lib/node-static.js:193
if (req.headers['if-none-match'] === headers['Etag'] &&
^
TypeError: Cannot read property 'headers' of undefined

I made a request with Node.js and did not bother setting any headers. node-static wasn't able to handle this case. It's not a big deal, but thought I'd mention it.

I plan on patching this as soon as I have time if somebody else does not beat me to it.

http server for static files (slow response from external ip)

i'm trying to use node.js for this task
var static = require('node-static');
var file = new(static.Server)(__dirname+'/../public', { cache: 3600 });
require('http').createServer(function (request, response) {
request.addListener('end', function () {
file.serve(request, response);
});
}).listen(8080);
and with this code i have slow response time (downloading time).
if i make request to localhost, everything is fine and quick.
but when i open url from another pc in our netework.
many requests have bigger time... localhost = 10-20ms, external request = 200+ms
http://i42.fastpic.ru/big/2012/0817/92/e60f7242b5b9c9dc2428db4e00c98d92.jpg
you can see in this image top example is local request, and bottom - external.
this is not our network problem, because this static content is tested with apache server, and there is no difference between local and external requests

Explain why a builtin cache is a good idea

Please explain why buffering static file data in memory is a good idea, and provide comparative benchmarks proving it. Most modern kernels already do this for you (see the 'cache' value in free(1)); caching in user space in addition is almost always a waste of memory.

error

Hej guys, I'm getting the following error message from node.

This happens every now and then and is in my eyes completely random. Sometimes it happens after hours of normal operation.

It also makes the complete node static server crash.


buffer.js:522
throw new Error('targetStart out of bounds');
^
Error: targetStart out of bounds
at Buffer.copy (buffer.js:522:11)
at exports.Server.stream.fs.createReadStream.on.on.on.pipe.end (/home/jasper/server/node_modules/node-static/lib/node-static.js:255:23)
at EventEmitter.emit (events.js:126:20)
at ReadStream._emitData (fs.js:1365:10)
at afterRead (fs.js:1347:10)
at Object.wrapper as oncomplete


My code is only as follows:


var static = require('node-static');

var fileServer = new(static.Server)('/home/jasper/website');

var server = require('http').createServer(function (request, response) {
request.addListener('end', function () {

    fileServer.serve(request, response);

});

}).listen(80);


Thanks for the help!

README errors

fileServer.serveFile('/not-found.html', request, response);

doesn't work since serveFile had a status and headers.

Separate cache and max-age

It would be nice to separate out the in-memory caching option from the cache-control max-age header. I plan to use varnish for caching, gzipping, but would like to set the max-age still via node-static.

David

Support for directory listings?

It'd be nice if there were a way to enable auto-generated directory listings, ala Apache AutoIndex/IndexOptions. 'Something to make it possible to easily browse a directory tree.

gzip handling serves stale .gz files

If .gz files are found, they should not be served if they are older then the file originally requested. As they are stated anyway, that should not add performance drawbacks, but prevent outdated documents beeing served.

Additionally, a user attached callback could be invoked, which may create a recent .gz file or issue a warning to some log.

Not a bug, merely a small missing feature that may do big headaches.

Example on synopsis doesn't work

I get the error:

livestats/vendor/node-static/lib/node-static.js:246
}).pipe(res, { end: false });
^
TypeError: Object [object Object] has no method 'pipe'

Ideas? I have looked source and googled the error, can't find a solution :(

Enable POST messages

I'm using node static to host a Facebook Application. Inside the iframe, Facebook sends a POST request to the iframe and kills the WebServer. Is it possible to enable POST messages too?

Does not work with node 0.2.3

Hi,

node-static bails out immediately with node 0.2.3 (0.2.2 is OK).

Here is the error:

/usr/local/lib/node/.npm/node-static/0.5.1/package/lib/node-static.js:239
chunk.copy (buffer, offset, 0);

Would be cool, if you could fix this or let me know if I should look into it.

Cannot find node-static

Looks like the main property was removed from package.json in 0.6.0 causing require('note-static') to throw

Multiple ports

Hi,

I was wondering about multiple instances and ports.

It would be very neat for start 2 or more instances just by running static and having port incremented if already used.

What do you think ?

Does this work?

The following just hangs in Node 0.10.1. It's like response.end is never being called.

var static = require('node-static');
var fileServer = new static.Server(__dirname + '/public');

require('http').createServer(function (request, response) {
    request.addListener('end', function () {
        fileServer.serve(request, response, function (err, result) {
            if (err) { // There was an error serving the file
                sys.error("Error serving " + request.url + " - " + err.message);

                // Respond to the client
                response.writeHead(err.status, err.headers);
                response.end();
            }
        });
    });
}).listen(3005);

Updated example for readme

Hello,

I was trying to get 404 page serving working, and I noticed that this example throws errors, but when I substitute the line above it, it works great

broken one:

require('http').createServer(function (request, response) {
request.addListener('end', function () {
fileServer.serve(request, response, function (e, res) {
if (e && (e.status === 404)) { // If the file wasn't found
fileServer.serveFile('/not-found.html', request, response);
}
});
});
}).listen(8080);

working one:

require('http').createServer(function (request, response) {
request.addListener('end', function () {
fileServer.serve(request, response, function (e, res) {
if (e && (e.status === 404)) { // If the file wasn't found
fileServer.serveFile('/error.html', 404, {}, request, response);
}
});
});
}).listen(8080);

file serving is broken for png files, possibly other files too.

using v0.3.0 and latest version of node-static

when i try to serve png files for a website, they work the first time. the second time i try to access those files (presumably when they are stored in a cache) it returns badly formatted data.

this is actually really critical, please try to look at this asap. thanks!

gzip

I added gzip support in .htaccess, but I still couldn't make it work. Is there any way to serve Gzip files using node-static?

ref :
"AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x-javascript application/javascript"

Creating a file server with an absolute path triggers an error on serving files

I am using node-static v0.5.1. I create the server like so:

var fileServer = new static.Server(root_directory);

… with root_directory set as follows:

var root_directory = path.normalize(path.join(__dirname, '..'));

This returns a path like "/Volumes/SecureDisk/code/my-project".

Upon serving file by calling fileServer.serve(), I always get an error:

http:572
var statusLine = "HTTP/1.1 " + statusCode.toString() + " "
^
TypeError: Cannot call method 'toString' of null
at ServerResponse.writeHead (http:572:45)
at [object Object].finish (/Volumes/Main/Users/antoine/local/lib/node/.npm/node-static/0.5.1/package/lib/node-static.js:108:17)
at /Volumes/Main/Users/antoine/local/lib/node/.npm/node-static/0.5.1/package/lib/node-static.js:165:14
at /Volumes/Main/Users/antoine/local/lib/node/.npm/node-static/0.5.1/package/lib/node-static.js:215:33
at [object Object]. (/Volumes/Main/Users/antoine/local/lib/node/.npm/node-static/0.5.1/package/lib/node-static.js:245:17)
at [object Object].emit (events:26:26)
at fs:640:12
at node.js:769:9

I've fixed this in my case by changing line 232 of node-static.js from:

        fs.createReadStream(path.join(pathname || '.', file), {

to:

        fs.createReadStream(file, {

In my case pathname was always null and path.join('.', '/Volumes/SecureDisk/code/my-project') was returning a wrong path since the starting / was removed, which made node-static not find the file anymore.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.