随手整个NodeJS文件服务器

Code

'use strict';

const url = require('url');
const fs = require('fs');
const http = require('http');
const querystring = require('querystring');
const os = require('os');

const shareFolder = __dirname + '/Share/';

let server = http.createServer((req, res) => {
    let requestPath = url.parse(req.url).path;
    requestPath = querystring.unescape(requestPath);
    let filePath = shareFolder + requestPath;
    fs.stat(filePath, (e, stats) => {
        if(e) {
            res.writeHead(404, {
                'Content-Type': 'text/plain'
            });
            res.end('404 not found');
        } else {
            if (stats.isFile()) {
                let file = fs.createReadStream(filePath);
                res.writeHead(200, {
                    'Content-Type': 'application/octet-stream'
                });
                file.pipe(res);
            } else {
                fs.readdir(filePath, (e, files) => {
                    let htmlContent = '';
                    htmlContent += '<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">';
                    htmlContent += '<style>html{background-color:#f8f9fa}body{box-sizing:border-box;margin:5vh auto;padding:20px;width:90vw;height:90vh;max-width:600px;border-radius:4px;background-color:#fff;box-shadow:rgba(0,0,0,.14) 0 2px 2px 0,rgba(0,0,0,.12) 0 1px 5px 0,rgba(0,0,0,.2) 0 3px 1px -2px}a:hover{background-color:rgba(0,0,0,.05)}a{display:block;color:#1a73e8;text-decoration:none;line-height:1.9em}</style>';
                    htmlContent += `<h1>${requestPath}</h1><hr>`;
                    if (requestPath == '/') {
                        requestPath = '';
                    }
                    for (let file of files) {
                        let relativelyFilePath = requestPath + '/' + file;
                        let localFile = shareFolder + relativelyFilePath;
                        if (fs.statSync(localFile).isFile()) {
                            htmlContent += `<a download href="${relativelyFilePath}">${file}</a>`;
                        } else {
                            htmlContent += `<a href="${relativelyFilePath}">${file}/</a>`;
                        }
                    }
                    res.writeHead(200, {
                        'Content-Type': 'text/html'
                    });
                    res.end(htmlContent);
                });
            }
        }
    });
});

function getIpv4() {
    let interfaces = os.networkInterfaces();
    for (let key of Object.keys(interfaces)) {
        for (let item of interfaces[key]) {
            if ('IPv4' == item.family && item.internal == false) {
                return item.address;
            }
        }
    }
    return null
}

let ip = getIpv4();
let port = 8888;
server.listen(port, ip);
console.log('Server is running on [' + ip + ':' + port + ']');