【问题标题】:Why won't this node.js script stay open in the terminal?为什么这个 node.js 脚本不会在终端中保持打开状态?
【发布时间】:2012-09-25 21:11:19
【问题描述】:

我想知道如何在不将node script_name.js 输入终端的情况下运行此脚本。当我从终端启动脚本时会显示提示,但是当我尝试将脚本作为程序运行时(从文件管理器,而不是命令行),它只是打开和关闭终端,而不显示提示。

#!/usr/local/bin/node

var prompt = require('prompt');

//var stuff = require("./stuff");

  prompt.start();

  prompt.get(['username', 'email'], function (err, result) {
    if (err) { return onErr(err); }
    console.log('Command-line input received:');
    console.log('  Username: ' + result.username);
    console.log('  Email: ' + result.email);
  });

  function onErr(err) {
    console.log(err);
    return 1;
  }

这是该程序的预期输出(带输入):

anderson@anderson-Ideapad-Z560:~/AeroFS/node.js examples$ node node_prompt_demo.js
prompt: username:  blah
prompt: email:  blah@example.com
Command-line input received:
  Username: blah
  Email: blah@example.com

【问题讨论】:

  • 当我从终端启动脚本时,它运行完美,但当我从桌面或文件管理器中选择“在终端中运行”时它不起作用。我仍然不明白为什么选择“在终端中运行”时无法使用命令行提示。
  • 另外,这个问题可能是相关的(虽然我认为它是针对 bash 脚本,而不是 node.js):askubuntu.com/questions/20330/…
  • 为了澄清,我已经设置了脚本作为应用程序运行的权限。当我使用“node name_of_script.js”启动脚本时,它会显示正确的输出并给出正确的提示,但是当我尝试通过单击“在终端中运行”来运行脚本时,终端只会打开和关闭。
  • 这是一个相关的问题(但肯定不是重复的):stackoverflow.com/questions/4806571/…
  • 它可能与未连接到您正在运行它的终端有关,而是与您从哪里运行它有关。只是猜测

标签: node.js ubuntu


【解决方案1】:

这几乎肯定与控制 tty 有关。我猜你正在使用的文件管理器没有给你一个stdin 附加到任何东西,它只是在没有任何输入的情况下退出。

最好的办法是把它包装在一个程序中,给它一个有效的stdin。例如,在 Mac 上,我在 Terminal.app 中运行节点脚本,因此它始终获得有效的标准输入。应该能够在 XWindows 中做类似的事情。如果您没有使用窗口管理器,您也可以尝试使用“expect”和“screen”。这些的组合应该可以满足您的需求。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-28
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多