Coder Social home page Coder Social logo

static's Introduction

koa-static

NPM version Build status Test coverage License Downloads

Koa static file serving middleware, wrapper for koa-send.

Installation

$ npm install koa-static

API

import Koa from "koa"; // CJS: require('koa');
import serve from "koa-static"; // CJS: require('koa-static')
const app = new Koa();
app.use(serve(root, opts));
  • root root directory string. nothing above this root directory can be served
  • opts options object.

Options

  • maxage Browser cache max-age in milliseconds. defaults to 0
  • hidden Allow transfer of hidden files. defaults to false
  • index Default file name, defaults to 'index.html'
  • defer If true, serves after return next(), allowing any downstream middleware to respond first.
  • gzip Try to serve the gzipped version of a file automatically when gzip is supported by a client and if the requested file with .gz extension exists. defaults to true.
  • brotli Try to serve the brotli version of a file automatically when brotli is supported by a client and if the requested file with .br extension exists (note, that brotli is only accepted over https). defaults to true.
  • setHeaders Function to set custom headers on response.
  • extensions Try to match extensions from passed array to search for file when no extension is sufficed in URL. First found is served. (defaults to false)

Example

const serve = require("koa-static");
const Koa = require("koa");
const app = new Koa();

// $ GET /package.json
app.use(serve("."));

// $ GET /hello.txt
app.use(serve("test/fixtures"));

// or use absolute paths
app.use(serve(__dirname + "/test/fixtures"));

app.listen(3000);

console.log("listening on port 3000");

See also

License

MIT

static's People

Contributors

3imed-jaberi avatar brizer avatar cap32 avatar cesarandreu avatar dionoid avatar fossprime avatar greenkeeperio-bot avatar haoxins avatar hiwanz avatar jonathanong avatar kenany avatar mattfelske avatar mishelen avatar pensierinmusica avatar plasmapower avatar rhavar avatar robinqu avatar sarsamurmu avatar tejasmanohar avatar tj 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

static's Issues

duplicated URLs serving index.html

Hello,

About html files and the fact both http://app/ and http://app/index.html serve the same index.html, is there a way to prevent from serving the second route?

I guess redirecting using a router is an option, but it requires extra router processing on each request,

Thanks!

Issue: Sending static files with version numbers

I tried to put version numbers on my static files as query param to avoid browser caching but looks like this approach wont work.

In my template I got /css/style.css?v=20140823160055 but this.path here will always refer to the file without query param /css/style.css and send will fail to load resource from disk. Same goes for static-cache.

Is there a Koa way to avoid browser caching but still achieve server side caching ?

Cannot serve nested paths?

I am trying to use koa-static to serve a basic JS file located in a structure like this-

-> dist
--> js
----> client.js
-> server.js

my server.js file is pretty straightforward as well-

var koa = require('koa'),
    router = require('koa-router'),
    serve = require('koa-static');

//create our app
var server = koa();
server.use(serve(__dirname + '/dist',{defer:true}));
server.use(router(server));

//start the server
server.listen(3000,"localhost");

However, this configuration always returns 404 requesting http://localhost:3000/dist/js/client.js. If I change the serve expression to be the relative ".", it works fine, however this is obviously not the desired behavior.

server.use(serve('.',{defer:true}));

I am using

    "koa": "^0.8.0",
    "koa-router": "^3.7.0",
    "koa-static": "^1.4.7",

Any ideas?

Serving name.html files under /name as well as /name.html ?

Any plans to support serving static html files on their "basename path"? That is for example http-server, github pages, and others, serve .html files both under /name.html and /name by default, so the index page would be accessible at:

  • /
  • /index
  • /index.html

And a non-index page at:

  • /page
  • /page.html

For me specifically I need to save my html files with an .html extension, serve them as simply as possible (static folder serve), and view them through an URL without the .html extension (since it's cleaner and a common pattern for wikis).

option for stat precedence

right now it stats upstream, but an option to stat downstream might be nice, for example it's not uncommon to want to serve statics first and completely ignore subsequent middleware (causing multiple builds etc), but what we have now incurs less overhead so that's ideal in some cases

Specify a default 404 file

Can we get an option to set a 404 file for requests that 404? It can definitely default to false, but if set to a file path then serve that file path in the body. This would be especially helpful for almost static sites being run by koa and koa middleware.

v1.4.x β†’ 1.5.0 breaking change due to defaulting opts.format to true

0e70310 introduces a breaking change by defaulting opts.format = true which introduces koa-send's new v2.0.0 behavior which can be seen in the highlighted lines in this diff: koajs/send@bfd4cbc#diff-168726dbe96b3ce427e7fedce31bb0bcR70

I recommend removing that opts.format = true defaulting behavior and republishing the minor version.

Illustration:

app.use(require('koa-static')('public'));
app.use(route.get('/', function*() {
  this.body = 'hello world';
}));
  • In v1.4.x, GET / will render hello world since / is a directory and just short-circuits with 404.
  • In v1.5.0, GET / will attempt to serve public/index.html and 404 if it doesn't exist. The / route cannot be accessed.

range support

through other middleware perhaps, since we have uncorked streams

how to use two folders to render

Hi,
In a yeoman generated project, it has app and bower_components folders, index.html is in app while angular.js is in bower_component, I use following code, but it found the index.html, not angular.js:

var serve = require('koa-static')
var koa = require('koa')
var app = koa()

app.use(serve('app'))
app.use(serve('bower_components'))

app.listen(3000);

index.html refer to angular.js as πŸ‘

 <script src="bower_components/angular/angular.js"></script>

How to make above code works in this kind of set up? Thanks.

doesn't work with ES6 (via babel-node)

static is a reserved word in ES6, so import static from 'koa-static' fails to transpile:

> babel-node --harmony index.js

/Users/boris/foobar/node_modules/babel/node_modules/babel-core/lib/babel/helpers/parse.js:80
    throw err;
          ^
SyntaxError: /Users/boris/foobar/index.js: The keyword 'static' is reserved (4:7)
  3 | import route from 'koa-route'
> 4 | import static from 'koa-static'

related to #32

Should we add a base directory option?

How else do we serve the local folder to, say, /static instead of /?

The only way I can think of is to create a local folder ./public/static/ and put everything in there instead. Are there any other ways?

named gen function...

would be nice to have the generator function named as per the guide... really helps debugging... (change is too tiny for a PR 😝)

custom header support

That would be nice it can set custom headers.
I'd like to set Access-Control-Allow-Origin header for asset files(bootstrap fonts).

rework send lib

the stream-ish nature bundles too much logic into the streaming portion, making it hard to handle errors properly here

Trouble serving index.html

I somehow can't get it running. If I send a request to / the following route gets triggered:

route.get('/', function *() {
  app.use(serve(__dirname + '.'));
});

but no index.html is sent. I've checked for the __dirname value and have correctly placed an index.html file in there. Am I doing anything wrong?

no 304 status

            this.header['cache-control'] = file.cacheControl || 'public, max-age=' + file.maxAge;
            if (this.fresh)
                return this.status = 304

automatically server `.gz` files

Hey. Can we modify this middleware in the way that if a static gziped file exists and the browser has the support for gzip then the header is automatically added and the .gz file is served instead of the original file?

Example:

if (precompiled .gz asset file path exists)
  this.body = myfile.js.gz
else
  this.body = myfile.js
end

Version 3.0 ?

I've gone through and butchered the source code, making it behave as I think it should. The result is here:

koa-better-static

There's a few breaking changes, but I think it's a clear improvement for the vast majority of use cases.
If you guys are amenable to it, I'd encourage to pull my version in as koa-static v3.

fix ENOENT

should just yield next;, but we can't use events for this

Unexpected strict mode reserved word

Running in strict mode

/koa-rest/node_modules/koa-static/index.js:36
    return function *static(next){
                     ^^^^^^
SyntaxError: Unexpected strict mode reserved word
    at exports.runInThisContext (vm.js:69:16)
    at Module._compile (module.js:432:25)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:349:32)
    at Function.Module._load (module.js:305:12)
    at Module.require (module.js:357:17)
    at require (module.js:373:17)
    at Object.<anonymous> (/Users/hemanth/labs/live-mongo/server/koa-rest/app.js:5:13)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)

//cc @jonathanong

Difference with koa-send

Hi,

Sorry for the silly question, I'm trying to figure out... what is the difference between koa-static and koa-send?

The two packages seem to be very similar, and I'm getting confused about which one to use.

Thanks!

directories without a trailing slash

Would be nice to mimic most static file servers and not require a trailing slash for directories, so that you could do both:

/directory
/directory/

Without having to care (since users aren't likely to type the trailing slash when sharing URLs to things) and they would both work.

fails on node v5.7.0

Until reverting to node node v5.6.0, I kept getting 'malicious path' error on node v5.7.0

(this is probably a node issue, but someone needs to debug koa/koa-send/koa-static to figure out where it is)

.mp4 video unable to play in Safari

Hello,

I got an error when I open a .mp4 file in browser which is hosted by koa-static, here is the message in terminal:

Error: write EPIPE
      at exports._errnoException (util.js:746:11)
      at WriteWrap.afterWrite (net.js:775:14)

Chrome can play the video, but Safari cannot play it,
and when I open the video in either Chrome or Safari, the error always appears.

Env:

  • nodeJs v0.12.4
  • koa v0.21.0
  • koa-static v1.4.9

allow overriding maxage per path

I'm serving up an Angular app and I want to heavily cache my static assets but have no cache on my index.html page.

At the moment the maxage setting applies to all files in the served directory.

I needed this for myself so I've forked the project and will issue a pull request shortly

maxage is not in force

Here is my code:

var staticServer = require('koa-static');
app.use(staticServer(__dirname+'/static', {maxAge: 365*24*60*3600}));

"maxAge" is not in force.

When i request a css file, the response header is :

Cache-Control:max-age=0

How do I specify the base directory

I want to do something like this:

app.use("/public", express.static(__dirname + "/public"));
app.use("/public2", express.static(__dirname + "/public2"));

Is this possible using koa?

respond only to GET and HEAD

While easy to hack around this should be the sane default. 200 OK in response to a POST/PUT/DELETE is very confusing to the client.

Get Warning with promise

Code

app.use(koa_static('./dist/', { index: 'index.html' }));
Warning: a promise was created in a  handler but was not returned from it
    at Object.eval (eval at <anonymous> (/home/farodin/Git/backend/node_modules/thenify/index.js:30:15), <anonymous>:9:8)
    at Object.<anonymous> (/home/farodin/Git/backend/node_modules/koa-send/index.js:72:28)
    at next (native)
    at onFulfilled (/home/farodin/Git/backend/node_modules/co/index.js:65:19)
    at processImmediate [as _immediateCallback] (timers.js:383:17)
From previous event:
    at Promise.then (/home/farodin/Git/backend/node_modules/sequelize/lib/promise.js:21:17)
    at next (/home/farodin/Git/backend/node_modules/co/index.js:100:51)
    at onFulfilled (/home/farodin/Git/backend/node_modules/co/index.js:69:7)
    at /home/farodin/Git/backend/node_modules/co/index.js:54:5
    at Object.co (/home/farodin/Git/backend/node_modules/co/index.js:50:10)
    at Object.toPromise (/home/farodin/Git/backend/node_modules/co/index.js:118:63)
    at next (/home/farodin/Git/backend/node_modules/co/index.js:99:29)
    at onFulfilled (/home/farodin/Git/backend/node_modules/co/index.js:69:7)
    at /home/farodin/Git/backend/node_modules/co/index.js:54:5
    at Object.co (/home/farodin/Git/backend/node_modules/co/index.js:50:10)
    at Object.toPromise (/home/farodin/Git/backend/node_modules/co/index.js:118:63)
    at next (/home/farodin/Git/backend/node_modules/co/index.js:99:29)
    at onFulfilled (/home/farodin/Git/backend/node_modules/co/index.js:69:7)
    at process._tickCallback (node.js:379:9)

Return 404 when file not found

When a file is not found status is set to 500 and not 404. A workaround is easy, but it'd be more elegant if it was supported out of the box.

Not sure if this needs adjusting in send/index.js:79 or if it should be overwritten here.

Doesn't find any files

Somehow koa-static can't find any files (e.g. /build.css) in the directory I specified. The code used to work but it broke today, and I can't figure out why. Could you help me out?

I've checked the file paths, opened all file permissions and reverted back to git checkpoints that used to work. Not sure what's going wrong here. Running node 0.11.12

DEBUG=koa-static:

Environment: development
Port: 1337
  <-- GET /
  --> GET / 200 18ms -
  <-- GET /build.css
  koa-static static "/home/yoshua/Code/server/server/../build" {} +0ms
  --> GET /build.css 404 4ms -
  <-- GET /favicon.ico
  --> GET /favicon.ico 200 8ms -

index.js:

'use strict';

/**
 * Module dependencies
 */

var responseTime = require('koa-response-time');
var compress = require('koa-compress');
var compose = require('koa-compose');
var base = require('./base/router');
var logger = require('koa-logger');
var helmet = require('koa-helmet');
var serve = require('koa-static');
var api = require('./api/index');
var http = require('http');
var koa = require('koa');

/**
 * Initialize variables.
 */

var ENV = process.env.NODE_ENV || 'development';
var PORT = process.env.port || 1337;
var app = koa();

/**
 * Allow for subdomain detection.
 */

app.subdomainOffset = 1;

/**
 * Middleware
 */

if ('test' != process.env.NODE_ENV) app.use(logger());
app.use(responseTime());
app.use(compress());
// app.use(helmet.defaults());

/**
 * Subdomain routes.
 */

app.use(function *(next) {
  switch (this.subdomains[0]) {

    case 'api': 
      return yield compose(api.middleware).call(this, next);
      break;

    case 'assets':
      var opts = __dirname + '/../build';
      return serve(opts);
      break;

    default:
      return yield compose(base.middleware).call(this, next);
      break;
  }
});

/**
 * Start listening.
 */

app.listen(PORT);
console.log('Environment: ' + ENV);
console.log('Port: ' + PORT);

make defer default

can't help but feel like this is a bad default, even though it matches connect

option to yield after send()

It seems like it would be useful for downstream middleware to be able to touch the response after req.body has been set, e.g. for post-processing files with trumpet.

(Forgive me if this is possible and I'm missing something here -- I'm just starting to play with koa...)

gzip compresstion

I think this module and also any module that serve static files need some mean of compression same as other web server technologies. In IIS this feature is on by default but completely under control of the system administrator and the programmer.
I think this is a feature request if there is no implementation yet.

Why yield next

I'm trying to get to grips with how koa is built. What is the purpose of yield next: index.js#L36

Am I right in thinking that static files are only served if the request is not handled by any other method? That seems really backwards compared to express's nice waterfalling semantics. It's simple to read an express app as "try this then try that then try that then try that" and it just stops once a method succeeds in handling the request. How would something like the following work:

var serve = require('static');
var koa = require('koa');
var app = koa();

app.use(serve('/first'));
app.use(serve('/second'));

app.listen(3000);

console.log('listening on port 3000');

fix for koa 0.2.1

status change breaks this, maybe it's time for the uber-ugly if (this.hasResponse)

Specify path for getting assets

Hello!
Right now, I'm currently kind of stuck. I would like to be able to load my assets like:
GET /public/myStyle.css

The problem is that everything defaults to the /. Is there a way in which I can specify the URL to grab static assets?

Can I use koa-static to serve individual files instead of directories? (e.x. serve assets folder on /assets and an config.toml file that's not in a served directory at /config.toml )

I can serve directories alright:

app.use(serve(pub_path));

But I'm at loss to figure out how to serve individual files.

Can I do this with koa-static? Or is there perhaps some simple way to do that with plain koa?

I guess I could do something like:

app.use(function *(){
  this.body = 'Hello World';
});

And replace 'Hello World' with the content of config.toml, but I'd rather use koa-static if possible.

get a 404

using example in readme, I get a 404 when fetching /style.less

What am I doing wrong?

I have a gulp task that uses webpack to package up my client-side code and puts it into the file [app_root]/build/public/bundle.js

My Koa server is also babel transpiled and then placed into [app_root]/build/index.js

Then I'm trying the following in my app:

import staticServe from 'koa-static'
import koa from 'koa'

let app = koa()

app.use(staticServe('public'))

And I keep getting the following error whenever I try to load my page and it tries to request the bundle.js file:

  BadRequestError: Invalid Request
  .
  .
  at Object.serve (/Users/mmarcus/WebstormProjects/Fanatics-3C/3c-middleware/node_modules/koa-static/index.js:41:14)

For the time being, I've gotten things to work with the following, but it's obviously a hack and breaks koa's handling of 404's for requests to the /public folder, giving me TypeError: Cannot read property 'Symbol(Symbol.iterator)' of undefined...

app.use(function* (next) {
  if (this.request.path.indexOf('/public') === 0) {
    yield staticServe(`${__dirname}`)
  } else {
    yield next
  }
})

Please help?

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.