0

我对很陌生,它似乎很容易使用,但是当使用命令行获取一个值并返回该值以在另一个包中使用时.js,它似乎比我预期的要难。

长话短说,我使用了一个包 ( akamai-ccu-purge) 来成功输入要在网络上清除的文件。

包中使用它来使其更具动态性。

在使用了几次尝试之后,var stdin = process.openStdin();我实际上发现了另一个名为的npmPrompt,它似乎更容易。不过,这两种方式似乎都有同样的问题。

节点似乎不想停止输入。即使我首先调用了该模块,它似乎也想自动进行清除而不等待输入。它实际上到达了我应该输入文件的地步,但它没有等待。

我在这里的理解或使用中肯定遗漏了一些东西,我做错了什么?

到目前为止,我的代码是:

var purgeUrl = require('./getUrl2');  

var PurgerFactory = require('../../node_modules/akamai-ccu-purge/index'); // this is the directory where the index.js of the node module was installed

// area where I placed the authentication tokens 
var config = {
  clientToken: //my tokens and secrets akamai requires
};

// area where urls are placed. More than one can be listed with comma separated values 
var objects = [
  purgeUrl // I am trying to pull this from the getUrl2 module
];

// Go for it! 
var Purger = PurgerFactory.create(config);

Purger.purgeObjects(objects, function(err, res) {
  console.log('------------------------');
  console.log('Purge Result:', res.body);
  console.log('------------------------');
  Purger.checkPurgeStatus(res.body.progressUri, function(err, res) {
    console.log('Purge Status', res.body);
    console.log('------------------------');
    Purger.checkQueueLength(function(err, res) {
      console.log('Queue Length', res.body);
      console.log('------------------------');
    });
  });
});

getUrl2模块如下所示:

var prompt = require('../../node_modules/prompt'); 
  // 
  // Start the prompt 
  // 
  prompt.start();

  // 
  // Get property from the user 
  // 
  prompt.get(['newUrl'], function (err, result) {
    // 
    // Log the results. 
    // 
    console.log('Command-line input received:');
    console.log('  http://example.com/custom/' + result.newUrl);
    var purgeUrl = 'http://example.com/custom/' + result.newUrl;
    console.log(purgeUrl);
    module.exports = purgeUrl;
  });

再次感谢您的帮助!

4

2 回答 2

2

我可能只允许getURL2公开一个将在主模块中调用的方法。例如:

// getURL2

var prompt = require('../../node_modules/prompt'); 

module.exports = {
  start: function(callback) {

    prompt.start();

    prompt.get(['newUrl'], function (err, result) {
      // the callback is defined in your main module
      return callback('http://example.com/custom/' + result.newUrl);
    });

  }
}

然后在你的主模块中:

require('./getUrl2').start(function(purgeURL) {
  // do stuff with the purgeURL defined in the other module
});

实现可能会有所不同,但从概念上讲,您需要使需要用户某种输入的第二个模块作为该输入的结果而发生。回调是执行此操作的常用方法(Promises 也是如此)。但是,由于prompt不一定公开需要 Promise 的方法,您可以使用普通的旧回调来完成。

于 2016-01-01T23:55:44.373 回答
2

您可能还想四处搜索有关使用 Node.js 编写命令行工具(有时称为 CLI)或命令行应用程序的文章。我发现以下文章在尝试自己解决这个问题时很有帮助:

http://javascriptplayground.com/blog/2015/03/node-command-line-tool/

此外,命令行参数模块对我来说效果很好(尽管还有许多其他模块可供选择):

https://www.npmjs.com/package/command-line-args

祝你好运!

于 2016-01-11T14:27:18.047 回答