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

前端 未结 30 1848
攒了一身酷
攒了一身酷 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:19

    If you are intrested in ultra-light http server without any prerequisites you should have a look at: mongoose

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

    If you do not want to use ready tool, you can use the code below, as demonstrated by me at https://developer.mozilla.org/en-US/docs/Node_server_without_framework:

    var http = require('http');
    var fs = require('fs');
    var path = require('path');
    
    http.createServer(function (request, response) {
        console.log('request starting...');
    
        var filePath = '.' + request.url;
        if (filePath == './')
            filePath = './index.html';
    
        var extname = path.extname(filePath);
        var contentType = 'text/html';
        switch (extname) {
            case '.js':
                contentType = 'text/javascript';
                break;
            case '.css':
                contentType = 'text/css';
                break;
            case '.json':
                contentType = 'application/json';
                break;
            case '.png':
                contentType = 'image/png';
                break;      
            case '.jpg':
                contentType = 'image/jpg';
                break;
            case '.wav':
                contentType = 'audio/wav';
                break;
        }
    
        fs.readFile(filePath, function(error, content) {
            if (error) {
                if(error.code == 'ENOENT'){
                    fs.readFile('./404.html', function(error, content) {
                        response.writeHead(200, { 'Content-Type': contentType });
                        response.end(content, 'utf-8');
                    });
                }
                else {
                    response.writeHead(500);
                    response.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
                    response.end(); 
                }
            }
            else {
                response.writeHead(200, { 'Content-Type': contentType });
                response.end(content, 'utf-8');
            }
        });
    
    }).listen(8125);
    console.log('Server running at http://127.0.0.1:8125/');
    

    UPDATE If you need to access your server from external demand/file, you need to overcome the CORS, in your node.js file by writing the below, as I mentioned in a previous answer here

    // Website you wish to allow to connect
    response.setHeader('Access-Control-Allow-Origin', '*');
    
    // Request methods you wish to allow
    response.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    
    // Request headers you wish to allow
    response.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    
    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    response.setHeader('Access-Control-Allow-Credentials', true);
    

    UPDATE

    As Adrian mentioned, in the comments, he wrote an ES6 code with full explanation here, I just re-posting his code below, in case the code gone from the original site for any reason:

    const http = require('http');
    const url = require('url');
    const fs = require('fs');
    const path = require('path');
    const port = process.argv[2] || 9000;
    
    http.createServer(function (req, res) {
      console.log(`${req.method} ${req.url}`);
    
      // parse URL
      const parsedUrl = url.parse(req.url);
      // extract URL path
      let pathname = `.${parsedUrl.pathname}`;
      // based on the URL path, extract the file extention. e.g. .js, .doc, ...
      const ext = path.parse(pathname).ext;
      // maps file extention to MIME typere
      const map = {
        '.ico': 'image/x-icon',
        '.html': 'text/html',
        '.js': 'text/javascript',
        '.json': 'application/json',
        '.css': 'text/css',
        '.png': 'image/png',
        '.jpg': 'image/jpeg',
        '.wav': 'audio/wav',
        '.mp3': 'audio/mpeg',
        '.svg': 'image/svg+xml',
        '.pdf': 'application/pdf',
        '.doc': 'application/msword'
      };
    
      fs.exists(pathname, function (exist) {
        if(!exist) {
          // if the file is not found, return 404
          res.statusCode = 404;
          res.end(`File ${pathname} not found!`);
          return;
        }
    
        // if is a directory search for index file matching the extention
        if (fs.statSync(pathname).isDirectory()) pathname += '/index' + ext;
    
        // read file from file system
        fs.readFile(pathname, function(err, data){
          if(err){
            res.statusCode = 500;
            res.end(`Error getting the file: ${err}.`);
          } else {
            // if the file is found, set Content-type and send data
            res.setHeader('Content-type', map[ext] || 'text/plain' );
            res.end(data);
          }
        });
      });
    
    
    }).listen(parseInt(port));
    
    console.log(`Server listening on port ${port}`);
    
    0 讨论(0)
  • 2020-11-22 13:22

    connect could be what you're looking for.

    Installed easily with:

    npm install connect
    

    Then the most basic static file server could be written as:

    var connect = require('connect'),
        directory = '/path/to/Folder';
    
    connect()
        .use(connect.static(directory))
        .listen(80);
    
    console.log('Listening on port 80.');
    
    0 讨论(0)
  • 2020-11-22 13:22

    There is another static web server that is quite nice: browser-sync.

    It can be downloaded using node package manager:

    npm install -g browser-sync
    

    After installation, navigate to the project folder in the cmd prompt and just run the following:

    browser-sync start --server --port 3001 --files="./*"
    

    It will start catering all the files in the current folder in the browser.

    More can be found out from BrowserSync

    Thanks.

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

    Here's another simple web server.

    https://www.npmjs.com/package/hostr

    Install

    npm install -g hostr
    

    Change working director

    cd myprojectfolder/
    

    And start

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

    You also asked why requests are dropping - not sure what's the specific reason on your case, but in overall you better server static content using dedicated middleware (nginx, S3, CDN) because Node is really not optimized for this networking pattern. See further explanation here (bullet 13): http://goldbergyoni.com/checklist-best-practice-of-node-js-in-production/

    0 讨论(0)
提交回复
热议问题