Basic static file server in NodeJS

后端 未结 8 744
盖世英雄少女心
盖世英雄少女心 2020-11-28 20:06

I\'m trying to create a static file server in nodejs more as an exercise to understand node than as a perfect server. I\'m well aware of projects like Connect and node-stati

相关标签:
8条回答
  • 2020-11-28 20:30

    How about this pattern, which avoids checking separately that the file exists

            var fileStream = fs.createReadStream(filename);
            fileStream.on('error', function (error) {
                response.writeHead(404, { "Content-Type": "text/plain"});
                response.end("file not found");
            });
            fileStream.on('open', function() {
                var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
                response.writeHead(200, {'Content-Type': mimeType});
            });
            fileStream.on('end', function() {
                console.log('sent file ' + filename);
            });
            fileStream.pipe(response);
    
    0 讨论(0)
  • 2020-11-28 20:35

    I made a httpServer function with extra features for general usage based on @Jeff Ward answer

    1. custtom dir
    2. index.html returns if req === dir

    Usage:

    httpServer(dir).listen(port);
    

    https://github.com/kenokabe/ConciseStaticHttpServer

    Thanks.

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