Git Product home page Git Product logo

node-static-alias's Introduction

node-static-alias

npm GitHub issues David license

Serve static file which is not requested file. (e.g. file.min.js is requested, serve file.js)
node-static-alias wraps (inherits) the useful module node-static, and this adds the alias option to that.
This works like the Alias mapping or the mod_rewrite of Apache. It looks like DirectoryIndex too. And this can check the file exists or not.

  • Serve file.js instead of file.min.js which is not made yet, in the test phase.
  • Serve the outside files of the document-root which are shared by multiple web sites in one machine.
  • Serve the default page which is not index.html when */ is requested.

Synopsis

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

// Document-Root: './public' directory
var fileServer = new staticAlias.Server('./public', {
  alias: {
    match: '/path/to/file.min.js',
    serve: '/path/to/file.js'
  }
});

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

Usage

The alias option is added to the node-static via using require('node-static-alias') instead of require('node-static'). See node-static to use it.

alias

The alias included in the constructor options is an Alias-Rule Object, or an array which includes multiple Alias-Rule Objects.

  alias: {
    match: /file\.min\.(?:js|css)$/,
    serve: '/path/to/file.<% suffix %>'
  }

Or

  alias: [
    {
      match: '/path/to/file.min.js',
      serve: '/path/to/file.js'
    },
    {
      match: 'suffix=png',
      serve: '../outer/<% fileName %>',
      allowOutside: true
    }
  ]

The Alias-Rule Object can have following properties.

match

Type: string, RegExp, function or Array

Specify one of below or an Array which includes multiple things of those.
If one or more things match, the serve is parsed. If anything doesn't match, it goes to next an Alias-Rule. If all Alias-Rules don't match, it tries to serve the requested file.

  • string:
    If the requested path is equal to this string, it's matched.
    Or, this can be parameter=value format (e.g. suffix=png). See Parameters. If the value is equal to the specified parameter, it's matched.
  alias: [
    {
      match: '/path/to/file.min.js',
      serve: '/path/to/file.js'
    },
    // Image files are not made yet.
    {
      match: 'suffix=png',
      serve: '/path/to/dummy.png'
    }
  ]
  • RegExp:
    The RegExp which tests the requested path.
  // These image files are not made yet.
  alias: {
    match: /\/(?:foo|bar)\.png$/,
    serve: '/path/to/dummy.png'
  }
  • function:
    The function which returns true or false. The Object which has parameters is passed to this function. See Parameters. Also, current request instance and response instance are passed.
    In the function, this refers to own instance.
  // Kick direct access from outside web site.
  alias: {
    match: function(params, request, response) {
      console.log(request.url + ' was requested, in the path ' + this.root);
      return params.suffix === 'jpg' &&
        params.referer.indexOf('http://mysite.com/') !== 0;
    },
    serve: '/path/to/denial.jpg'
  }

serve

Type: string, function or Array

Specify one of below or an Array which includes multiple things of those.
By default, the first file which exists is chosen to try to serve. See force. If anything doesn't exist, it goes to next an Alias-Rule. If all files of Alias-Rules don't exist, it tries to serve the requested file.

  • string:
    The absolute path or relative path from the document-root of the file to serve.
    This can include parameters like <% parameter %>. See Parameters.
  // directoryIndex isn't index.html
  alias: {
    match: /\/$/,
    serve: '<% absPath %>/default.html'
  }

NOTE: If the first character of this string is / (it might be parameter), this string is absolute path. This / doesn't point the document-root. It is the root of the local filesystem. If you want the relative path from the document-root, don't specify leading /, or add . to left of leading /.

  • function:
    The function which returns the absolute path or relative path from the document-root of the file to serve.
    The Object which has parameters is passed to this function. See Parameters. Also, current request instance and response instance are passed.
    In the function, this refers to own instance.
  // Minified files are not made yet.
  alias: {
    match: /\.min\.(?:js|css)$/,
    serve: function(params, request, response) {
      response.setHeader('X-serve-from', this.root);
      return params.absDir + '/' +
        params.basename.replace(/\.min$/, '.') + params.suffix;
    }
  }
  // Compile unwatched SASS now.
  alias: {
    match: 'suffix=css',
    serve: function(params) {
      require('exec-sync')('sass ' +
        params.absDir + '/' + params.basename + '.scss:' + params.absPath);
      return params.absPath;
    }
  }

force

Type: boolean

If true is specified, the first file in the serve is chosen to try to serve without checking it's existing or not. And if it doesn't exist, a 404 error occurs. Default is false.
This is used to prevent another file from being chosen unintentionally.

allowOutside

If true is specified, serving the outside files of the document-root is allowed. Default is false.

  // Shared files.
  alias: {
    match: /^\/common_lib/,
    serve: '/path/to/lib/<% fileName %>',
    allowOutside: true
  }

NOTE: If you specify true in the public server, you should specify the absolute path to the serve. Otherwise the user might access to the file that must be hidden from them.

Parameters

The string parameter=value can be specified to the match, and the string <% parameter %> can be specified to the serve.
And also, the Object which has parameters is passed to function which specified to the match and the serve.
These parameters are below.

  • reqUrl
    The URL which is requested by the user. e.g. /path/to/file.ext?key1=value1&key2=value2
  • reqPath
    The path which is requested by the user. e.g. /path/to/file.ext
    This might be a directory. e.g. /
  • reqDir
    The path to a directory which is part of reqPath. e.g. /path/to
  • absPath
    The absolute path to a requested file. e.g. /var/www/public/path/to/file.ext
  • absDir
    The absolute path to a directory which is part of absPath. e.g. /var/www/public/path/to
  • fileName
    The file name of a requested file. e.g. file.ext
    This might be a directory name e.g. to
    If the document-root is requested, this is empty string.
  • basename
    The part of the file name except file-suffix. (. isn't included) e.g. file
  • suffix
    The part of the file name which is extracted file-suffix. (. isn't included) e.g. ext
  • reqQuery
    The URL query string which is part of reqUrl. e.g. key1=value1&key2=value2
  • Parsed query string
    Pairs of a key beginning with a query_ and a value. e.g. query_key1: value1, query_key2: value2 from reqQuery above
    An array is extracted and each key is given [INDEX]. e.g. query_key[0]: value1, query_key[1]: value2 from key=value1&key=value2
  • Request Headers
    The HTTP Request Headers from the client. These are lower-cased. e.g. referer, user-agent, etc.

Logging

The logger included in constructor options is a Logger instance of the standard Logging Library (e.g. log4js) which has info method or log method.

var log4js = require('log4js');
var logger = log4js.getLogger('node-static-alias');
logger.setLevel(log4js.levels.INFO);

var fileServer = new staticAlias.Server('./public' {
  alias: { ... },
  logger: logger
});

You can specify a simple Object which has info method or log method (e.g. console or util).
Most easy:

var fileServer = new staticAlias.Server('./public' {
  alias: { ... },
  logger: console
  //logger: require('util') // Add timestamp
});

Add project name: (But, you probably use your favorite library.)

var fileServer = new staticAlias.Server('./public' {
  alias: { ... },
  logger: {log: function() {
    var util = require('util');
    console.log('[node-static-alias] ' +  util.format.apply(util, arguments));
  }}
});

Log message example:

(/) Requested: "/var/public"
(/file.min.css) Requested: "/var/public/file.min.css"
(/file.min.css) For Serve: "/var/public/file.css" alias[3] match[1] serve[0]
(/file.min.js) Requested: "/var/public/file.min.js"
(/file.min.js) For Serve: "/var/public/file.js" alias[2] match[0] serve[1]

The (path) is the path which is requested by the user. The [number] means an index of an Array.

Files list in the Directory

This example generates a list of files and directories in requested directory when the user accessed the directory. This works like the mod_autoindex of Apache.

That looks like:
ss

The statsFilelist is required.

npm install stats-filelist

Load that and some core modules.

var filelist = require('stats-filelist'),
  path = require('path'),
  fs = require('fs');

Specify for alias:

alias: {
  match: function(params) {
    try {
      return fs.statSync(params.absPath).isDirectory();
    } catch (error) {
      return false; // Ignore "Not found" etc.
    }
  },
  serve: function(params) {
    var indexPath = path.join(params.absPath, '.index.html');
    fs.writeFileSync(indexPath,
      '<html><body><ul>' +
      filelist.getSync(params.absPath, /^(?!.*[/\\]\.index\.html$).+$/, false)
        .map(function(stat) {
          var relPath = stat.name + (stat.isDirectory() ? '/' : '');
          return '<li><a href="' + relPath + '">' + relPath + '</a></li>';
        }).join('') +
      '</ul></body></html>');
    return indexPath;
  }
}

node-static-alias's People

Contributors

anseki avatar

Stargazers

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

Watchers

 avatar  avatar  avatar

node-static-alias's Issues

Feature Request: include full request URL in parameters

It would be helpful to additionally have the full request URL (as exposed by req.url, like /foo/bar/baz.jpg?bam=1) available in the "Parameters" that are accessible for matching, both in the string (key=value) form and in the function form. Of course, it should also be available for the serve specification, like <% ... %>. I propose this new parameter be called "reqURL" to fit with "reqPath" and others.

I had a use-case where I wanted to serve a different file depending on if there was a ?SID=... query parameter in the URL. I had to work-around the lack of that information available for matching by pre-parsing req.url and manually overriding it, before calling serve(..).

Feature Request: support asynchrony for `match(..)` / `serve(..)` handler functions

Both match(..) and serve(..) expect an immediate return value.

But would you consider a minimal modification (not a breaking change, I don't think) where if either returns a promise, it's waited on to resolve before moving on?

For example:

// ..
{
   async match(params,req,res) {
      var result = await Router.check(params.reqUrl);
      if (url) return true;
      else return false;
   },
   async serve(params,req,res) {
      let reqBody = JSON.parse(await getStream(req));
      if (reqBody.addExtension) return params.reqPath + ".html";
      else return params.reqPath;
   }
}
// ..

In this contrived example, matching (true / false) is asynchronous because the router may be looking up a route from a database or other async persistence layer, and serving is asynchronous because it needs to read something from the request-body (retrieved asynchronously) to decide what filename to use.

Right now, I'm having to do this kind of stuff as pre-processing, doing the asynchronous waiting and adding properties to the req object, all before calling node-static-alias. It would be nice if that async logic could just be embedded into match(..) / serve(..).

I think all that needs to happen is that those handlers need to see if a promise is returned, and if so, simply call then(..) on it to wait. I don't think returning a promise would have been valid prior, so this doesn't seem like a breaking change.

"Cannot set headers..." error intermittently

I'm seeing this error show up in my log frequently but intermittently (like once every 5-10 requests, about once every 5 minutes or so):

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:471:11)
    at ServerResponse.writeHead (_http_server.js:231:21)
    at Server.finish (/tmp/site/node_modules/node-static/lib/node-static.js:125:17)
    at finish (/tmp/site/node_modules/node-static/lib/node-static.js:170:14)
    at /tmp/site/node_modules/node-static/lib/node-static.js:337:13
    at streamFile (/tmp/site/node_modules/node-static/lib/node-static.js:382:13)
    at ReadStream.<anonymous> (/tmp/site/node_modules/node-static/lib/node-static.js:375:17)
    at ReadStream.emit (events.js:182:13)
    at fs.close (fs.js:2161:14)
    at FSReqWrap.oncomplete (fs.js:152:20)

I have logged out what URL is being requested that's causing this error, but it's a normal URL that when I try it, it works fine for me, and does not cause this error in the log. So it has to be something other than the URL (not sure, maybe some other headers?).

Anyway, my code is very basic... it looks like this:

var nodeStaticAlias = require("node-static-alias");
var staticServer = new nodeStaticAlias.Server(path.join(__dirname,"static"),{
        serverInfo: "my-server",
        cache: 86400,
        gzip: true,
        alias: [
                {
                        match: /[^]/,
                        serve: "index.html",
                },
        ],
});

And in my HTTP request handler:

res.setHeader("Strict-Transport-Security","max-age=" + 1E9 + "; includeSubdomains");

// unconditional, permanent HTTPS redirect
if (req.headers["x-forwarded-proto"] !== "https") {
    res.writeHead(301,{
        "Cache-Control": "public, max-age=31536000",
        Expires: new Date(Date.now() + 31536000000).toUTCString(),
        Location: `https://${req.headers["host"]}${req.url}`
    });
    res.end();
}
else if (["GET","HEAD"].includes(req.method)) {
    staticServer.serve(req,res);
}
else {
    res.writeHead(404);
    res.end();
}

Any thoughts on how I can track down what's causing this and fix it?

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.