简体   繁体   English

我可以从命令行运行sailsjs控制器方法吗?

[英]Can I run sailsjs controller methods from the command line?

I am writing an application with Sailsjs which includes a scraper. 我正在用Sailsjs编写一个包含刮刀的应用程序。 Currently I'm calling the scraper functions from the browser using the default Routes but I think it would be better if I can privately call the needed methods from the terminal. 目前我正在使用默认路由从浏览器调用scraper函数,但我认为如果我可以从终端私下调用所需的方法会更好。 Is it possible to do this? 是否有可能做到这一点?

You can use the Sails console to access controller methods, but you'd have to either provide fake req and res objects as arguments, or create controller functions which didn't require req and res , which isn't good practice. 您可以使用Sails控制台访问控制器方法,但您必须提供伪reqres对象作为参数,或者创建不需要reqres控制器函数,这不是一个好习惯。 A better approach would be to move the scraping code into a service , which is a library that Sails makes globally available for you. 更好的方法是将抓取代码移动到服务中 ,该服务是Sails为您提供全局可用的库。 For example, if you had a file /api/services/ScraperService.js with: 例如,如果您有一个文件/api/services/ScraperService.js

module.exports = {

   scrape: function (url, fileToSaveResultsTo) {
      // do scraping and save to file
   }

}

then you could call the service from within a controller or in the Sails console with: 然后你可以从控制器 Sails控制台中调用服务:

ScraperService.scrape("http://google.com", "results.txt");

Start the console in your terminal with sails console . 使用sails console在终端中启动sails console

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

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