使用 Nodejs 提供静态文件

问题描述 投票:0回答:3

我只是想创建一个 Node js 服务器,它为我的文件夹中的静态文件提供服务

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

const server = http.createServer((req,res)=>{
const readStream = fs.createReadStream('./static/index.html');
res.writeHead(200,{'Content-type':'text/html'});
readStream.pipe(res);
res.end();
});

server.listen(5000,()=>{
console.log("server running at port 5000");
 })

我有一个名为

static
的文件夹,其中包含一个名为
index.html
的文件,其中包含简单的 html 代码。 服务器运行成功,但没有发送响应

node.js
3个回答
1
投票

尝试使用 fs.readFile 而不是 fs.createReadStream

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

const server = http.createServer((req, res) => {
    fs.readFile(__dirname + '/static/index.html', (err, data) => {
        if (err) {
            res.writeHead(404);
            res.end(JSON.stringify(err));
            return;
        }

        res.writeHead(200);
        res.end(data);
    })
});

server.listen(5000, () => {
    console.log("> server on 5000");
});

1
投票

正如评论部分提到的,

.createReadStream will end the stream automatically when the end of the file is reached
所以我们只需要删除
res.end()

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

const server = http.createServer((req,res)=>{
const readStream = fs.createReadStream('./static/index.html');
res.writeHead(200,{'Content-type':'text/html'});
readStream.pipe(res);
res.end();
});

server.listen(5000,()=>{
console.log("server running at port 5000");
})

0
投票

这是我的终极 Node.JS 静态 http 服务器:

const http = require('http');
const url = require('url');
const fs = require('fs');
const path = require('path');
const port = process.argv[2] || 3000;

const rootDir = './public'

http.createServer(function (req, res) {
  console.log(`${req.method} ${req.url}`);

  // parse URL
  const parsedUrl = url.parse(req.url);
  // extract URL path
  let pathname = `${rootDir}${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',
    '.gif': 'image/gif',
    '.wav': 'audio/wav',
    '.mp3': 'audio/mpeg',
    '.svg': 'image/svg+xml',
    '.pdf': 'application/pdf',
    '.doc': 'application/msword'
  };

  fs.exists(pathname, function (exist) {
    if(!exist) {
      res.statusCode = 404;
      res.end(`File ${pathname} not found!`);
      return;
    }

    if (fs.statSync(pathname).isDirectory()) pathname += '/index' + ext;

    fs.readFile(pathname, function(err, data){
      if(err){
        res.statusCode = 500;
        res.end(`Error getting the file: ${err}.`);
      } else {
        res.setHeader('Content-type', map[ext] || 'text/plain' );
        res.end(data);
      }
    });
  });


}).listen(parseInt(port));

console.log(`Server listening on port ${port}`);

它使用公共目录作为根目录,但您可以将其更改为您自己的目录

© www.soinside.com 2019 - 2024. All rights reserved.