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

前端 未结 30 1846
攒了一身酷
攒了一身酷 2020-11-22 12:30

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



        
相关标签:
30条回答
  • 2020-11-22 13:08

    One-line™ Proofs instead of promises

    The first is http-server, hs - link

    npm i -g http-server   // install
    hs C:\repos            // run with one line?? FTW!!
    

    The second is serve by ZEIT.co - link

    npm i -g serve         // install
    serve C:\repos         // run with one line?? FTW!!
    

    Following are available options, if this is what helps you decide.

    C:\Users\Qwerty>http-server --help
    usage: http-server [path] [options]
    
    options:
      -p           Port to use [8080]
      -a           Address to use [0.0.0.0]
      -d           Show directory listings [true]
      -i           Display autoIndex [true]
      -g --gzip    Serve gzip files when possible [false]
      -e --ext     Default file extension if none supplied [none]
      -s --silent  Suppress log messages from output
      --cors[=headers]   Enable CORS via the "Access-Control-Allow-Origin" header
                         Optionally provide CORS headers list separated by commas
      -o [path]    Open browser window after starting the server
      -c           Cache time (max-age) in seconds [3600], e.g. -c10 for 10 seconds.
                   To disable caching, use -c-1.
      -U --utc     Use UTC time format in log messages.
    
      -P --proxy   Fallback proxy if the request cannot be resolved. e.g.: http://someurl.com
    
      -S --ssl     Enable https.
      -C --cert    Path to ssl cert file (default: cert.pem).
      -K --key     Path to ssl key file (default: key.pem).
    
      -r --robots  Respond to /robots.txt [User-agent: *\nDisallow: /]
      -h --help    Print this list and exit.
    
    C:\Users\Qwerty>serve --help
    
      Usage: serve.js [options] [command]
    
      Commands:
    
        help  Display help
    
      Options:
    
        -a, --auth      Serve behind basic auth
        -c, --cache     Time in milliseconds for caching files in the browser
        -n, --clipless  Don't copy address to clipboard (disabled by default)
        -C, --cors      Setup * CORS headers to allow requests from any origin (disabled by default)
        -h, --help      Output usage information
        -i, --ignore    Files and directories to ignore
        -o, --open      Open local address in browser (disabled by default)
        -p, --port   Port to listen on (defaults to 5000)
        -S, --silent    Don't log anything to the console
        -s, --single    Serve single page applications (sets `-c` to 1 day)
        -t, --treeless  Don't display statics tree (disabled by default)
        -u, --unzipped  Disable GZIP compression
        -v, --version   Output the version number
    

    If you need to watch for changes, see hostr, credit Henry Tseng's answer

    0 讨论(0)
  • 2020-11-22 13:08

    You can try serve-me

    Using it is so easy:

    ServeMe = require('serve-me')();
    ServeMe.start(3000);
    

    Thats all.

    PD: The folder served by default is "public".

    0 讨论(0)
  • 2020-11-22 13:09

    For a healthy increase of performance using node to serve static resources, I recommend using Buffet. It works similar to as a web application accelerator also known as a caching HTTP reverse proxy but it just loads the chosen directory into memory.

    Buffet takes a fully-bufferred approach -- all files are fully loaded into memory when your app boots, so you will never feel the burn of the filesystem. In practice, this is immensely efficient. So much so that putting Varnish in front of your app might even make it slower! 

    We use it on the codePile site and found an increase of ~700requests/sec to >4k requests/sec on a page that downloads 25 resources under a 1k concurrent user connection load.

    Example:

    var server = require('http').createServer();
    
    var buffet = require('buffet')(root: './file'); 
    
     
    
    server.on('request', function (req, res) {
    
      buffet(req, res, function () {
    
        buffet.notFound(req, res);
    
      });
    
    });
    
     
    
    server.listen(3000, function () {
    
      console.log('test server running on port 3000');
    
    });
    
    0 讨论(0)
  • 2020-11-22 13:09

    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);

    0 讨论(0)
  • 2020-11-22 13:10

    It isn't on NPM, yet, but I built a simple static server on Express that also allows you to accept form submissions and email them through a transactional email service (Sendgrid for now, Mandrill coming).

    https://github.com/jdr0dn3y/nodejs-StatServe

    0 讨论(0)
  • 2020-11-22 13:11

    In plain node.js:

    const http = require('http')
    const fs = require('fs')
    const path = require('path')
    
    process.on('uncaughtException', err => console.error('uncaughtException', err))
    process.on('unhandledRejection', err => console.error('unhandledRejection', err))
    
    const publicFolder = process.argv.length > 2 ? process.argv[2] : '.'
    const port = process.argv.length > 3 ? process.argv[3] : 8080
    
    const mediaTypes = {
      zip: 'application/zip',
      jpg: 'image/jpeg',
      html: 'text/html',
      /* add more media types */
    }
    
    const server = http.createServer(function(request, response) {
      console.log(request.method + ' ' + request.url)
    
      const filepath = path.join(publicFolder, request.url)
      fs.readFile(filepath, function(err, data) {
        if (err) {
          response.statusCode = 404
          return response.end('File not found or you made an invalid request.')
        }
    
        let mediaType = 'text/html'
        const ext = path.extname(filepath)
        if (ext.length > 0 && mediaTypes.hasOwnProperty(ext.slice(1))) {
          mediaType = mediaTypes[ext.slice(1)]
        }
    
        response.setHeader('Content-Type', mediaType)
        response.end(data)
      })
    })
    
    server.on('clientError', function onClientError(err, socket) {
      console.log('clientError', err)
      socket.end('HTTP/1.1 400 Bad Request\r\n\r\n')
    })
    
    server.listen(port, '127.0.0.1', function() {
      console.log('                                                                    
    0 讨论(0)
提交回复
热议问题