Node.js quick file server (static files over HTTP)

2019-01-01 14:01发布

Is there Node.js ready-to-use tool (installed with npm), that would help me expose folder content as file server over HTTP.

Example, if I have

D:\Folder\file.zip
D:\Folder\file2.html
D:\Folder\folder\file-in-folder.jpg

Then starting in D:\Folder\ node node-file-server.js I could access file via

http://hostname/file.zip
http://hostname/file2.html
http://hostname/folder/file-in-folder.jpg

Why is my node static file server dropping requests? reference some mystical

standard node.js static file server

If there's no such tool, what framework should I use?

Related: Basic static file server in NodeJS

27条回答
闭嘴吧你
2楼-- · 2019-01-01 14:42

const http = require('http');
const fs = require('fs');
const url = require('url');
const path = require('path');


let mimeTypes = {
  '.html': 'text/html',
  '.css': 'text/css',
  '.js': 'text/javascript',
  '.jpg': 'image/jpeg',
  '.png': 'image/png',
  '.ico': 'image/x-icon',
  '.svg': 'image/svg+xml',
  '.eot': 'appliaction/vnd.ms-fontobject',
  '.ttf': 'aplication/font-sfnt'
};



http.createServer(function (request, response) {
  let pathName = url.parse(request.url).path;
  if(pathName === '/'){
    pathName = '/index.html';
  }
  pathName = pathName.substring(1, pathName.length);
  let extName = path.extName(pathName);
  let staticFiles = `${__dirname}/template/${pathName}`;

      if(extName =='.jpg' || extName == '.png' || extName == '.ico' || extName == '.eot' || extName == '.ttf' || extName == '.svg')
      {
          let file = fr.readFileSync(staticFiles);
          res.writeHead(200, {'Content-Type': mimeTypes[extname]});
          res.write(file, 'binary');
          res.end();
      }else {
        fs.readFile(staticFiles, 'utf8', function (err, data) {
          if(!err){
            res.writeHead(200, {'Content-Type': mimeTypes[extname]});
            res.end(data);
          }else {
            res.writeHead(404, {'Content-Type': 'text/html;charset=utf8'});
            res.write(`<strong>${staticFiles}</strong>File is not found.`);
          }
          res.end();
        });
      }
}).listen(8081);

查看更多
回忆,回不去的记忆
3楼-- · 2019-01-01 14:45

For people wanting a server runnable from within NodeJS script:

You can use expressjs/serve-static which replaces connect.static (which is no longer available as of connect 3):

myapp.js:

var http = require('http');

var finalhandler = require('finalhandler');
var serveStatic = require('serve-static');

var serve = serveStatic("./");

var server = http.createServer(function(req, res) {
  var done = finalhandler(req, res);
  serve(req, res, done);
});

server.listen(8000);

and then from command line:

  • $ npm install finalhandler serve-static
  • $ node myapp.js
查看更多
牵手、夕阳
4楼-- · 2019-01-01 14:45

I know it's not Node, but I've used Python's SimpleHTTPServer:

python -m SimpleHTTPServer [port]

It works well and comes with Python.

查看更多
登录 后发表回答