2013-06-25 79 views
0

我創建了一個簡單的模塊,將一些數據發佈到返回消息和其他結果的外部服務。從JS/Node模塊獲取返回值

我想用摩卡測試這個,但我發現很難理解如何訪問返回的值。

我可以看到它在控制檯中記錄,但不知道如何將其設置爲變量。正如你不會懷疑的,我是一個新手javacripter。我相信這很簡單,我只是看不到。

我的模塊:

module.exports = { 

    foo: function(id,serial) { 
    var querystring = require('querystring'); 
    var http = require('http'); 
    var fs = require('fs'); 
    var post_data = querystring.stringify({ 
     'serial' : serial, 
     'id': id 
    }); 

    var post_options = { 
     host: 'localhost', 
     port: '8080', 
     path: '/api/v1/status', 
     method: 'POST', 
     headers: { 
      'Content-Type': 'application/x-www-form-urlencoded', 
      'Content-Length': post_data.length 
     } 
    }; 

    var post_req = http.request(post_options, function(res) { 
     res.setEncoding('utf8'); 
     res.on('data', function (chunk) { 
      console.log(chunk); 
      return chunk; 
     }); 
    }); 

    post_req.write(post_data); 
    post_req.end(); 
    } 
} 

而且我已經叫這個有:

describe('Functions and modules', function() { 
    it('does some shizzle', function(done) { 
    var tools = require('../tools'); 
    chunk = ''; 
    id = 123; 
    serial =456; 
    tools.foo(id,serial); 
    chunk.should.equal....... 
    }); 
}); 

基本上,我需要從tools.foo返回消息(ID,序列),但塊比熄滅空白的東西。

在我的終端,我可以看到:

{"message":"This device is still in use","live":"nop"} 

回答

1

您無法訪問「返回」值你在其他語言會的方式。節點中的Http請求是異步的,並且不返回它們的值。相反,您傳遞一個回調函數,或者在同一個請求的範圍內創建一個回調函數。例如,你可以完成你的函數是這樣的:(我去掉了一些填料)

module.exports = { 

    foo: function (options, data, callback) { 
     'use strict'; 

     var completeData = ''; 

     var post_req = http.request(options, function (res) { 
      res.setEncoding('utf8'); 

      res.on('data', function (chunk) { 
       console.log(chunk); 
       completeData += chunk; 
       return chunk; 
      }); 

      res.on('end', function() { 
       callback(completeData); 
       //You can't return the data, but you can pass foo a callback, 
       //and call that function with the data you collected 
       //as the argument. 
      }); 

     }); 

     post_req.write(data); 
     post_req.end(); 
    } 
}; 

function someCallBackFunction (data) { 
    console.log("THE DATA: " + data); 
} 

var someOptions = "whatever your options are"; 
var someData = "whatever your data is"; 

module.exports.foo(someOptions, someData, someCallBackFunction); 

如果你的定義是在同一範圍內的功能,你也可以直接foo的範圍內訪問someCallBackFunction,但傳球在回調中是更好的風格。

+0

啊,我是一個紅寶石主義者的死亡贈品;)好的,現在就給它一個鏡頭。歡呼 – simonmorley

+0

我現在明白了這一點。這給了我一個錯誤:'TypeError:undefined不是一個函數'參考回調 – simonmorley

+0

這意味着你沒有傳遞足夠的參數給foo。您需要將「callback」參數傳遞給一個變量,該變量已被定義爲一個帶有一個參數的函數。我通過對foo的示例調用修改了我的示例。 – ChrisCM