NodeJs如何在其他事件之后向客户端发送响应

时间:2018-02-07 20:16:47

标签: node.js

我注意到我只是学习nodejs而且我的代码有问题,即我希望服务器在解析网页之后将响应返回给客户端。

    var request = require('request');
    var fs = require('fs');
    var http = require('http');
    var _HttpContent = "";
    var pageindex = 1;
    var itemindex = 1;
    var ServerPort = 1880;




    function ParsePages() {

        request('https://url/', function (error, response, body) {
            console.log('error:', error);
            console.log('statusCode:', response && response.statusCode);

            var lines = body.split('\n');

            lines.forEach(function (line) {
                //console.log(line);
                if (line.indexOf("__listing_ItemsStoreState") > 0) {
                    var start = line.indexOf("__listing_ItemsStoreState") + "__listing_ItemsStoreState = ".length;
                    var stop = line.indexOf("};");
                    var result = line.substring(start, stop + 1);

                    obj = JSON.parse(result);

                    for (var i = 0; i < obj.itemsGroups[0].items.length; i++) {
                        _HttpContent = _HttpContent + itemindex + ") " + obj.itemsGroups[0].items[i].title.text + "<br>\n";
                        itemindex++;
                    }

                    pageindex++;
                    console.log("PageIndex: " + pageindex);

                    if (pageindex <= 4) {
                        ParsePages();
                    } else { 

                            res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
                            res.write(_HttpContent, 'utf8');
                            res.end();
                            _HttpContent = "";                      
                    }

                }
            });
        });
    }

    function onRequest(req, res) { 

        ParsePages(); 
    }

    const _HttpServer = http.createServer(onRequest).listen(ServerPort, (err) => {
        if (err) {
            return console.log('something bad happened', err)
        }

        console.log(`server is listening on locallhost:${ServerPort}`);
    });

你好..我注意到我只是在学习nodejs而且我的代码有问题,即我希望服务器在解析网页之后将响应返回给客户端。

0 个答案:

没有答案