是否有Node.js即用工具(与npm一起安装),可以帮助我通过HTTP将文件夹内容作为文件服务器公开。

例如,如果我有

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

然后从D:\Folder\node node-file-server.js开始我可以通过

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

为什么我的节点静态文件服务器丢弃请求?参考一些神秘的

标准node.js静态文件服务器

如果没有这样的工具,我应该使用什么框架?

相关:NodeJS中的基本静态文件服务器


当前回答

为了搜索者的利益,我喜欢Jakub g的答案,但需要一点错误处理。显然,正确处理错误是最好的,但这有助于防止站点在发生错误时停止。代码如下:

var http = require('http');
var express = require('express');

process.on('uncaughtException', function(err) {
  console.log(err);
});

var server = express();

server.use(express.static(__dirname));

var port = 10001;
server.listen(port, function() { 
    console.log('listening on port ' + port);     
    //var err = new Error('This error won't break the application...')
    //throw err
});

其他回答

如果您对超轻http服务器感兴趣,无需任何先决条件你应该看看:猫鼬

使用connect的简单静态服务器

var connect = require('connect'),
  directory = __dirname,
  port = 3000;

connect()
  .use(connect.logger('dev'))
  .use(connect.static(directory))
  .listen(port);

console.log('Listening on port ' + port);

另请参见将node.js用作简单的web服务器

还有一个非常好的静态web服务器:浏览器同步。

可以使用节点包管理器下载:

npm install -g browser-sync

安装后,在cmd提示符下导航到项目文件夹,然后运行以下命令:

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

它将开始处理浏览器中当前文件夹中的所有文件。

更多信息请访问BrowserSync

谢谢

如果您不想使用现成的工具,可以使用下面的代码,如我在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/');

更新如果您需要从外部需求/文件访问服务器,则需要通过编写以下内容来克服node.js文件中的CORS,正如我在前面的回答中提到的

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

更新

正如Adrian所提到的,在评论中,他写了一个ES6代码,并在这里进行了完整的解释,我只是在下面重新发布了他的代码,以防代码出于任何原因从原始站点消失:

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 extension. e.g. .js, .doc, ...
  const ext = path.parse(pathname).ext;
  // maps file extension 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 extension
    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}`);

const http=要求('http');常量fs=要求('fs');const url=require('url');常量路径=require('path');让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”:“appaction/vnd.ms fontobject”,“.ttf”:“应用程序/font sfnt”};http.createServer(函数(请求、响应){let pathName=url.parse(request.url).path;如果(路径名=='/'){pathName='/index.html';}pathName=pathName.substring(1,pathName.length);let extName=路径.extName(路径名);let staticFiles=`${__dirname}/template/${pathName}`;如果(extName==“.jpg”| | extName=“.png”| | ext Name=“.ico”| | extName=“.eot”| | extName=“.ttf”| | textName=“.svg”){let file=fr.readFileSync(静态文件);res.writeHead(200,{'Content-Type':mimeTypes[extname]});res.write(文件,'binary');res.end();}其他{fs.readFile(staticFiles,'utf8',函数(错误,数据){if(!err){res.writeHead(200,{'Content-Type':mimeTypes[extname]});res.end(数据);}其他{res.writeHead(404,{'Content-Type':'text/html;charset=utf8'});res.write(“<strong>${staticFiles}</strong>找不到文件。”);}res.end();});}}).听(8081);