-->

Node.js static file server logic (using Connect mi

2019-02-20 20:15发布

问题:

Let's say I have the following filesystem structure:

/app/            Main application folder
  /app.js        Server JS file ran by node.js
  /public        Folder containing files for public website (port 80)
    /index.html
    /js/
      /game.js
  /admin/        Folder containing files used by local network system (port X)
    /index.html
    /js/
      /screen.js
  /share/        Folder containing files to be used by public website OR lan
    /js/
      /jquery.js

The end result is that admin/index.html would look like:

<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript" src="/js/screen.js"></script>

That is, I'm loading two files from different locations. Basically, the thought here is "check if file is in /share, if not, try loading it from folder according to port".

And here's the current code I'm using:

var connect = require('connect'),
    sourcePublic = connect().use(
        connect.static(__dirname + '/public', { maxAge: 86400000 })
    ),
    sourceAdmin = connect().use(
        connect.static(__dirname + '/admin', { maxAge: 86400000 })
    ),
    sourceShare = connect().use(
        connect.static(__dirname + '/share', { maxAge: 86400000 })
    ),
    serverPublic = http.createServer(sourcePublic).listen(80),
    serverAdmin  = http.createServer(sourceAdmin).listen(90);
// ok, how do I use sourceShare?

PS: This system should be world-accessible through http://host/ (possibly a domain or static ip) AND accessible via the local network through http://host:90/.

While the stuff on port 90 won't damage the system (it's just an output screen), I'd rather if people would not be able to access it from outside (easily done by ensuring there is no port 90 forwarding between router and server).

回答1:

Connect middleware is stackable, so you can achieve the wanted result by simply stacking all the wanted handlers after each other.Public server gets the /public and /share handlers and admin gets the /admin and /share handlers.

So request to public server will search for the resource under /public folder if not found there then search under /share folder. And admin server does it similarly.

var connect = require('connect'),
    sourcePublic = connect().use(
        connect.static(__dirname + '/public', { maxAge: 86400000 })
    ).use(
        connect.static(__dirname + '/share', { maxAge: 86400000 })
    ),
    sourceAdmin = connect().use(
        connect.static(__dirname + '/admin', { maxAge: 86400000 })
    ).use(
        connect.static(__dirname + '/share', { maxAge: 86400000 })
    ),
    serverPublic = http.createServer(sourcePublic).listen(80),
    serverAdmin  = http.createServer(sourceAdmin).listen(90);