如何在不同的nodejs文件中调用函数

时间:2014-03-13 06:32:37

标签: node.js function http-post

我需要将函数sendPostData(postData)调用到fb.js中,因为当我运行post.js文件时我得到错误名称调用postData未定义,postData我在fb.​​js中定义我需要在post中获取postData .js如果你在post.js下面签到我编码req.write(postData); 我怎么称呼这个功能?

文件名 - fb.js

var https=require('follow-redirects').https; 


require('./post');

var args = process.argv.slice(2);
console.log('url:' + args[0]);

var host =args[0].match (/w.*m/)[0];
console.log('host: ' + host);
var path =args[0].match (/(\/d.*)/)[0];
console.log('path: ' + path);

var opti = { 
            host: host, 
            port: 443,
            path: path,
            headers: {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:25.0) Gecko/20100101 Firefox/26.0'}
            } 

var req=https.request(opti, function (res){ 
        //console.log('Status: ' + res.statusCode);
        var data=''; 

res.on('data',function(chunk){ 
        data += chunk 
        }); 
res.on('end',function(){ 

    //console.log('Data: ' + data);

           // console.log(data);
        var match=data.match(/Directory Results for(.*)\/li>/); 

        if (!match) {
        //console.log('Match not found');
        match=data.match(/selected"(.*?)fbD/);
        //console.log('Match: ' + match[0]);

        }
var postData = '';
var match1=match.toString().match(/<a>|\/directory\/people\/(.*?)">(.*?)<\/a>/g);   

match1=match1.removeDuplicates();

 for (var index = 0; index < match1.length; index++) { 
                    var link = match1[index];
                    link = link.substring(link.indexOf('"'),0);
                    link = 'http://www.facebook.com' + link;

                    postData += '&url=' + encodeURIComponent(link);
                    console.log(link);
            //sendPostData(postData)=postData;
                } 


        }); 

    }); 
Array.prototype.removeDuplicates = function (){
  var temp=new Array();
  this.sort();
  for(i=0;i<this.length;i++){
  if(this[i]==this[i+1]) {continue}

  else{

  temp[temp.length]=this[i];
  }
}
  return temp;
  }     


req.end();

文件名 - post.js

var querystring = require('querystring');
var http = require('http');

function sendPostData(postData) {
  var options = {
    host: 'staging.360social.me',
    port: 80,
    path: '/queueNewDirectoryPageUrls',
    method: 'POST'
};

var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  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.write(postData);
req.end();
}

1 个答案:

答案 0 :(得分:2)

首先,在您的post.js

exports.sendPostData=sendPostData;

fb.js

var p = require('./post');

然后调用它

p.sendPostData(postData);