Giter VIP home page Giter VIP logo

koa-files's Introduction

koa-files

A static files serving middleware for koa.

NPM Version Download Status Snyk Vulnerabilities Node Version

Installation

$ npm install koa-files

API

const Koa = require('koa');
const server = require('koa-files');

const app = new Koa();

// Static files server
app.use(server(root, options));
  • root root directory string. nothing above this root directory can be served.
  • options options object.

Options

acceptRanges?: boolean

  • Enable or disable accepting ranged requests. Disabling this will not send Accept-Ranges and ignore the contents of the Range request header. defaults to true.

cacheControl?: string

etag?: boolean

  • Enable or disable etag generation, defaults to true.

lastModified?: boolean

  • Enable or disable Last-Modified header, defaults to true. Uses the file system's last modified value. defaults to true.

ignore?: (path: string) => boolean

  • Set ignore rules. defaults to undefined.

defer?: boolean

  • If true, serves after await next(), allowing any downstream middleware to respond first. defaults to false.

Example

/**
 * @module server
 * @license MIT
 * @author nuintun
 */

'use strict';

const Koa = require('koa');
const server = require('koa-files');

const app = new Koa();
const port = process.env.PORT || 80;

/**
 * @function httpError
 * @param {NodeJS.ErrnoException} error
 * @returns {boolean}
 */
function httpError(error) {
  return /^(EOF|EPIPE|ECANCELED|ECONNRESET|ECONNABORTED)$/i.test(error.code);
}

// Static files server
app.use(server('tests', { cacheControl: 'public, max-age=31557600' }));

// Listen error event
app.on('error', error => !httpError(error) && console.error(error));

// Start server
app.listen(port, () => console.log(`> server running at: 127.0.0.1:${port}`));

Features

Support multipart range and download resumption.

License

MIT

koa-files's People

Contributors

nuintun avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

koa-files's Issues

Internally reusing the file sending capability

I'm writing a custom middleware that needs to send files. (I'm porting it from Express to Koa, actually.)

I'd like to reuse the capability from your middleware to send a specific file.

Here's a simplified example:

import { Middleware } from "koa";
import server from "koa-files";
import path from "node:path";
import fs from "node:fs";

export function myMiddleware(): Middleware {
  return (context, next) => {
    const rootPath = "/home/user/app/files";
    const fileName = "folder/file.jpg";
  
    console.log("exists", fs.existsSync(path.join(rootPath, fileName))); // true
  
    context.path = fileName; // I've also tried `context.url = filename` and `context.path = "/"+filename`
  
    server(rootPath)(context, next);
  };
}

I see "exists: true" on the console, so I know the file exists.

But the response on the page is always just "Not found".

I know it's probably unusual to create and call middleware from within another middleware - but the library doesn't export a function to just send a specific file on demand, and since my rootPath can't be determined at startup, I have to create and run the middleware every time. That would probably be fine, since your middleware doesn't do any heavy initialization.

But it just doesn't work. Any idea why?

Question about the error event handler.

Hi, great work on this. It seems much cleaner than koa-range and it's nice to see multipart support.

This is less of an issue and more of a question, or potentially a note that could be added to the docs, but I've been getting these connection reset errors trying to play videos from a node server using Chrome 81:

Error: write ECONNRESET
      at WriteWrap.onWriteComplete [as oncomplete] (internal/stream_base_commons.js:92:16)
      at handleWriteReq (internal/stream_base_commons.js:51:26)
      at writeGeneric (internal/stream_base_commons.js:143:15)
      at TLSSocket.Socket._writeGeneric (net.js:780:11)
      at TLSSocket.Socket._write (net.js:792:8)
      at doWrite (_stream_writable.js:441:12)
      at clearBuffer (_stream_writable.js:580:7)
      at TLSSocket.Writable.uncork (_stream_writable.js:336:7)
      at ServerResponse.OutgoingMessage.uncork (_http_outgoing.js:244:17)
      at connectionCorkNT (_http_outgoing.js:698:8)

This happens with every range request implementation I've tried, including both this and koa-range. Fortunately, it doesn't seem to be affecting playback at all.

I noticed you have an error event handler in your example that silences these, among others:

function httpError(error) {
  return /^(EOF|EPIPE|ECANCELED|ECONNRESET|ECONNABORTED)$/i.test(error.code);
}

// ...

// Listen error event
app.on('error', error => !httpError(error) && console.error(error));

So, my question is, what is the reasoning behind this, aside from just not clogging up logs with these things? Do we know why these are happening, and whether or not they might be a problem in a production environment?

It's been really hard to find information about this through either Google or Stack Overflow. Would you mind pointing me in the right direction, and maybe allowing me to add some notes about the answers I find to your README, for the sake of others?

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.