简体   繁体   English

从生成的进程访问Sails控制器

[英]Accessing a Sails controller from a spawned process

I'm trying to spawn a background service upon Sails' lift. 我正在尝试在Sails的电梯上生成后台服务。 Here's what I've come up with so far : 到目前为止,这是我想出的:

config/bootstrap.js : config/bootstrap.js

module.exports.bootstrap = function(cb) {

    sails.on('lifted', function() {
        var spawn = require('child_process').spawn;
        var worker = spawn('node', ['./worker.js']);
    });

    cb();

};

worker.js : worker.js

var sails = require('sails');

sails.controllers.MyController.myFunction(null, function(data) {
    console.log(data);
});

When I lift Sails, I get the following error : Cannot read property 'MyController' of undefined . 抬起Sails时,出现以下错误: Cannot read property 'MyController' of undefined

I tried without the require('sails') and without the sails.controllers in front of my controller's name, but then it throws me MyController is not defined . 我试着在控制器名称前没有require('sails') sails.controllers require('sails')且没有sails.controllers ,但随后抛出MyController is not defined

Any idea why I can't access my controller from the bootstrap function ? 知道为什么我无法从引导功能访问控制器吗?

You need to load or lift the Sails app in order to be able to access controllers, models, etc. See sails.load() and sails.lift() for more details. 您需要加载或提升Sails应用程序才能访问控制器,模型等。有关更多详细信息,请参见sails.load()sails.lift() So it'd be something like: 所以会是这样的:

var sails = require('sails');
sails.load(function(err, sails) {
   if (err) {
     // handle error and exit process
   }
   // sails is now fully loaded
   sails.controllers.my.myFunction(null, function(data) {
      console.log(data);
   }
});

Side note, it's also weird to run controller code outside of the context of a request. 旁注,在请求上下文之外运行控制器代码也很奇怪。 You probably should refactor that code into a service instead. 您可能应该将该代码重构为服务 And as @elssar notes above, controller identities are lowercased and the "controller" part is removed. 并且如上面的@elssar所述,控制器标识是小写的,并且“控制器”部分已删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM