在NodeJS中将对象传递给子文件的最佳方法是什么?

时间:2016-03-01 08:54:13

标签: node.js

例如,我有这样的代码:

var redis = require('redis');
var client = redis.createClient(port, host);

var Stash = require('./lib/stash');
var stash = new Stash(data);

stash.search()

search方法包含很少request个,其中我需要将数据保存到Redis。将client传递给回调的最佳方法是什么?

Stash.prototype.search = function(search) {
    var self = this;

    request(SEARCH_URL + '?' + querystring.stringify(this.params), function (error, response, body) {
        if (!error && response.statusCode == 200) {
            // Here i need REDIS
        }
    });
};

通过search方法作为参数然后添加到回调?基本上我需要在不止一个地方有Redis所以我需要做的就像PHP中的静态类。有可能或者可能在NodeJS中有一些特定的技术吗?

2 个答案:

答案 0 :(得分:2)

如何将redis上的所有操作保存在一个名为redisoperation.js的单独文件中。

var redis = require('redis');
var client;
exports.init = function init() {
    if (typeof client === 'undefined') {
        client = redis.createClient(port, host);
        client.on("ready", connectionEstablished);
        client.on("error", connectionError);
        client.on("end", connectionLost);
    }
}

exports.saveDataToRedis = function (data) {
    // save data to redis through client
}

exports.getDataFromRedis = function (key) {
    // get data from redis through client
}

App.js

// init the redis connection firstly
var rd = require('./redisoperation.js');
rd.init();

// other operation on redis through `rd.saveDataToRedis(d)` or `rd.getDataFromRedis(k)`

对于想要使用redis相关api的其他文件,可能需要redisoperation.js,如上所述,并调用它们。

require doc

  

模块在第一次加载后进行缓存。这意味着(除其他外)每次调用require('foo')将获得完全相同的返回对象,如果它将解析为同一文件。

您的评论中没有redisoperation.js的多个副本。

答案 1 :(得分:1)

如果在当前模块中定义了search函数,则没有更好的方法来使用客户端,而只是将其定义为模块根级别的变量。

目前,我认为最好的方法是使用Promise。使它成为您的搜索方法返回一个promise,然后在当前模块中定义该promise的回调。它看起来像这样:

stash.search().then(function(results) {
  //saveStuff is the made-up function. Use your redis API here to save stuff. If your saving logic was inside the search function before, you were doing something wrong.
  client.saveStuff(results);
})
.except(function(err) {
  //This is the reject handler.
  console.log(err);
});

如果您使用ES6承诺,搜索方法将如下所示:

function search() {
  //Resolve and reject are functions that mark promise as completed successfully or with error respectively. You can pass some data into them.
  return new Promise(function(resolve, reject) {
    //This is your async search logic (using request module).
    request('http://www.google.com', function (error, response, body) {
      if (!error && response.statusCode == 200) {
        //You may wanna transform response body somehow.
        resolve(body);
      } else {
        reject(error);
      }
    });
  });
}

您可以在此处阅读有关ES6承诺的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

相关问题