zoukankan      html  css  js  c++  java
  • 服务器端node.js

    实现一个文件服务器
    var fs = require('fs');
    var url = require('url');
    var path = require('path');
    var http = require('http');
    
    // 从命令行参数获取根目录,默认为当前目录
    var root = path.resolve(process.argv[2]||'.');
    // 创建服务器
    var server = http.createServer(function(req,res) {
        var pathname = url.parse(req.url).pathname;
        var filepath = path.join(root,pathname);
        //获取文件状态
        fs.stat(filepath,function(err,stats){
            if(!err && stats.isFile()) {
                res.writeHead(200);
                // 将文件流导向res
                fs.createReadStream(filepath).pipe(res);
            } else {
                // 发送404响应
                res.writeHead(404);
                res.end('404 Not Found');
            }
        })
    });
    
    server.listen(8080);
    console.log('server is running at http://127.0.0.1:8080/');
  • 相关阅读:
    usage of tmux docker
    mac. mysql
    使用ssh远程编辑
    systemd-udevadm
    iperf
    brctl
    NAT
    Linux 网络配置
    Linux 命令行快捷键
    sed 参数分析
  • 原文地址:https://www.cnblogs.com/wuting/p/9398631.html
Copyright © 2011-2022 走看看