2013-09-07 2 views
0

nodejs가있는 페이지의 페이지 소스를 검색해야하지만 검색 할 페이지가 항상 동일하지는 않습니다.노드 js를 사용하여 페이지 소스 검색하기

내가 듣고 그는 연결을받을 때 자신이 아닌 정의 페이지의 sourse를 가져 오지 load.js를 호출되고이 파일 server.js이 내 코드는 다음과 같습니다

server.js

var net = require('net'); 

var loadFb = require('./load.js'); 


var HOST = 'localhost'; 
var PORT = 9051; 


// Create a server instance, and chain the listen function to it 
// The function passed to net.createServer() becomes the event handler for the 'connection' event 
// The sock object the callback function receives UNIQUE for each connection 


net.createServer(function(sock) { 

    // We have a connection - a socket object is assigned to the connection automatically 
    console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort); 

    // Add a 'data' event handler to this instance of socket 
    sock.on('data', function(data) { 

     console.log('User request profile of: ' + data); 
     // Write the data back to the socket, the client will receive it as data from the server 


     //here I have to call test.js 

     //how 


     sock.write(data);  
    }); 

    // Add a 'close' event handler to this instance of socket 
    sock.on('close', function(data) { 
     console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort); 
    }); 

}).listen(PORT, HOST); 


console.log('Server listening on ' + HOST +':'+ PORT); 

다른 파일이 있습니다 :

var https = require('https'); 


var options = { 
    host: 'graph.facebook.com', 
    port: 443, 
    path: '/dario.vettore', 
    method: 'GET' 
    }; 

    var req = https.get(options, function(res) { 
    var pageData = ""; 
    res.setEncoding('utf8'); 
    res.on('data', function (chunk) { 
     pageData += chunk; 
     //console.log(pageData); 
     return pageData; 
    }); 

    res.on('end', function(){ 
     //response.send(pageData) 
    }); 
    }); 

가 어떻게 그것을 위해 두 번째 파일에서 페이지 소스를 가져 오지 두 번째 파일의 첫 번째 파일 (server.js)에서 요청할 수 있습니다,하지만 페이지 일 내가 변경할 수있는 소스를 얻으려면에서 .. 항상

감사

두 번째 파일에서

답변

0

동일하지 않고, 당신이 함수를 내보낼 (I 그 loadFb.js를라는 하나 있으리라 믿고있어) 코드를 바로 호출하는 것.

노드는 모듈을 캐시하므로 require() 코드는 한 번만 실행됩니다.

var https = require('https'); 

module.exports = function(path, callback) { 
    var options = { 
    host: 'graph.facebook.com', 
    port: 443, 
    path: path, 
    method: 'GET' 
    }; 

    var req = https.get(options, function(res) { 
    var pageData = ""; 
    res.setEncoding('utf8'); 
    res.on('data', function (chunk) { 
     pageData += chunk; 
    }); 
    res.on('end', function(){ 
     callback(pageData); 
    }); 
    }); 
}; 

그런 다음 첫 번째 파일에서이 같은 액세스 것 :

loadJs('/dario.vettore', function(pageData) { 
    console.log(pageData); 
}); 

당신이 모듈의 코드를 여러 번 실행할 수있는이 방법을

두 번째 파일은 다음과 같이 보일 것이다 , 다른 경로와.

+0

그레이트 !!! 내 영어로 죄송합니다. nodejs를 사용할 수 없습니다 ... 최대한 빨리 해결책을 찾으려고 노력합니다 !!!! –

관련 문제