美文网首页
Node.js - Web 服务器程序练习

Node.js - Web 服务器程序练习

作者: 萧沪椿Helson | 来源:发表于2017-09-02 15:43 被阅读0次
    var http = require('http')
    var url = require('url')
    var path = require('path')
    var fs = require('fs')
    
    var root = path.resolve(process.argv[2] || './static')
    
    console.log('Static root dir: ' + root)
    
    var server = http.createServer((request, response) => {
        var pathname = url.parse(request.url).pathname
        var filepath = path.join(root, pathname)
        fs.stat(filepath, (err, stats) => {
            if (!err && stats.isDirectory()) {
                fs.readdir(filepath, (err, files) => {
                    if (err) {
                        fail(request, response)
                        console.log('Wrong dir operation!')
                    } else if (files.includes('index.html')) {
                        filepath = path.join(filepath, 'index.html')
                        success(filepath, request, response)
                    } else if (files.includes('default.html')) {
                        filepath = path.join(filepath, 'default.html')
                        success(filepath, request, response)
                    }
                })
            } else if (!err && stats.isFile()) {
                success(filepath, request, response)
            } else {
                fail(request, response)
            }
        })
    })
    
    function success(filepath, request, response) {
        console.log('200' + request.url)
        response.writeHead(200)
        fs.createReadStream(filepath).pipe(response)
    }
    
    function fail(request, response) {
        console.log('404 ' + request.url)
        response.writeHead(404)
        response.end('404 Not Found')
    }
    
    server.listen(8080)
    
    console.log('Server is running at localhost:8080...')
    

    简单的 GET

    var http = require('http')
    
    http.get('http://localhost:8080/', (res) => {
        const { statusCode } = res;
        const contentType = res.headers['content-type'];
      
        let error;
        if (statusCode !== 200) {
          error = new Error('Request Failed.\n' +
                            `Status Code: ${statusCode}`);
        }
        if (error) {
          console.error(error.message);
          // consume response data to free up memory
          res.resume();
          return;
        }
      
        res.setEncoding('utf8');
        let rawData = '';
        res.on('data', (chunk) => { rawData += chunk; });
        res.on('end', () => {
          try {
            console.log(rawData);
          } catch (e) {
            console.error(e.message);
          }
        });
      }).on('error', (e) => {
        console.error(`Got error: ${e.message}`);
      });
    

    或者用 request 书写 GET 方法

    var http = require('http')
    
    var options = {
        port: 8080,
        path: '/',
        method: 'GET'
    };
    
    var req = http.request(options, function(res) {
        console.log('STATUS: ' + res.statusCode);
        console.log('HEADERS: ' + JSON.stringify(res.headers));
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            console.log('BODY: ' + chunk);
        });
    });
    
    req.on('error', function(e) {
        console.log('problem with request: ' + e.message);
    });
    
    req.end();
    

    点我查看完整代码

    相关文章

      网友评论

          本文标题:Node.js - Web 服务器程序练习

          本文链接:https://www.haomeiwen.com/subject/nakrjxtx.html