Node.js - Web 服務(wù)器程序練習(xí)

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...')

簡(jiǎn)單的 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 書(shū)寫(xiě) 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();

點(diǎn)我查看完整代碼

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,063評(píng)論 25 709
  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,569評(píng)論 19 139
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語(yǔ)法,類相關(guān)的語(yǔ)法,內(nèi)部類的語(yǔ)法,繼承相關(guān)的語(yǔ)法,異常的語(yǔ)法,線程的語(yǔ)...
    子非魚(yú)_t_閱讀 34,728評(píng)論 18 399
  • 最近線上線下人們都在討論白鹿原,我也不免又把那本書(shū)翻出來(lái)看了一遍,對(duì)比著電視的劇情,反復(fù)咀嚼陳忠實(shí)想要表達(dá)的...
    風(fēng)尚資訊閱讀 552評(píng)論 0 0
  • 我有太多的心事, 只在夜里夢(mèng)里向虛渺訴說(shuō), 因?yàn)檫B憂愁都是模糊的。 一件小事闖進(jìn)耳里,留在心里。 如同一個(gè)石子打在...
    _味道_閱讀 326評(píng)論 0 0

友情鏈接更多精彩內(nèi)容