节点模块导出返回未定义

我想创build一个节点模块来抓取一些post,但我得到一个未定义的错误。

Index.js

var request = require('request'); function getPosts() { var options = { url: 'https://myapi.com/posts.json', headers: { 'User-Agent': 'request' } }; function callback(error, response, body) { if (!error && response.statusCode == 200) { return JSON.parse(body); } } request(options, callback); } exports.posts = getPosts; 

testing/ index.js

 var should = require('chai').should(), myModule = require('../index'); describe('Posts call', function () { it('should return posts', function () { myModule.posts().should.equal(100); }); }); 

我错过了什么?

===错字修正后编辑===

看起来你实际上并没有“得到”callback是如何工作的。

你定义的callback将asynchronous激发,所以它不能用来按照你想要的方式返回一个值。 这样做的方法是让getPosts()函数实际上接受另一个函数,这是调用代码关心的callback函数。 所以你的testing看起来像这样:

 describe('Posts call', function(){ it('should have posts', function(done){ myModule.posts(function(err, posts){ if(err) return done(err); posts.should.equal(100); done(); }); } }); 

那么你的模块代码将是这样的,为了支持:

 var request = require('request'); function getPosts(callback) { var options = { url: 'https://myapi.com/posts.json', headers: { 'User-Agent': 'request' } }; function handleResponse(error, response, body) { if (!error && response.statusCode == 200) { return callback(null, JSON.parse(body)); } return callback(error); // or some other more robust error handling. } request(options, handleResponse); } exports.posts = getPosts; 

在那里可以有更好的error handling,比如确保JSON.parse正确,但是这应该给你一个想法。