Using pipe() in Node.js net

前端 未结 4 2137
长发绾君心
长发绾君心 2020-12-12 17:54

I\'m having trouble wrapping my head around the pipe function shown in several Node.js examples for the net module.

var net = require(\'net\');
         


        
4条回答
  •  情歌与酒
    2020-12-12 18:43

    Consider the following request handler

    var server = http.createServer(function(req, res){
         console.log('Request for ' + req.url + ' by method ' + req.method);
        if(req.method == 'GET'){
            var fileurl;
            if(req.url == '/')fileurl = '/index.html';
            else {
                fileurl = req.url;
            }
        }
        var filePath = path.resolve('./public'+fileurl);
        var fileExt = path.extname(filePath);
        if(fileExt == '.html'){
              fs.exists(filePath, function(exists){
            if(!exists){
              res.writeHead(404, {'Content-Type': 'text/html'});
              res.end('

    Error 404' + filePath + 'not found

    '); //the end() method sends content of the response to the client //and signals to the server that the response has been sent //completely return; } res.writeHead(200, {'Content-Type':'text/html'}); fs.createReadStream(filePath).pipe(res); }) } }

    The fs.createReadStream method reads the file in the given file path (public/index.html) and pipe() writes it to the response (res) for client's view.

提交回复
热议问题