【问题标题】:How to execute the shell-script in NodeJS and wait for it to display and get in the stream?如何在 NodeJS 中执行 shell 脚本并等待它显示并进入流?
【发布时间】:2017-04-18 15:23:02
【问题描述】:

我与控制台有硬件连接 但它适用于命令:

enter image description here

我创建 omron.sh 是因为我需要在 nodeJS 中运行它

#!/bin/sh

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/splincode/Develop/omron/c++_modules/libomron/omron-build/lib/
~/Develop/omron/usr/local/bin/omron_790IT_test

但我需要它在 NodeJS 中工作并写入流标准输出,但是,不起作用

server.js:

let http = require('http'), 
    fs = require('fs'),
    url = require('url'),
    path = require('path');

let server = new http.Server(); // EventEmitter

server.listen(8000, '127.0.0.1');
server.on("connection", () => console.log("connection"));
server.on('request', (request, response) => {

    console.log('.', request.url)

    let userUrl = decodeURIComponent(url.parse(request.url).pathname);
    let loadFile = false;

    switch(userUrl) {
        case '/': 
            userUrl += 'index.html';
            loadFile = true;
        break;

        case '/omron':

            console.log('omron')

            var util=require('util')
            var exec=require('child_process').spawn('sh', ['omron.sh']);

            // not work
            exec.stdout.on('data', (data) => {
              console.log(`stdout: ${data}`);
              response.end(`${data}`);
            }); 

        break;

        default: 
            loadFile = true;
        break;
    };


    if (userUrl === '/') userUrl += 'index.html';


    if (loadFile) {
        let pathname = path.normalize(path.join(__dirname, userUrl));
        fs.readFile(pathname, (err, content) => {
            let mime = require('mime').lookup(pathname);
            response.setHeader('Content-Type', `${mime}; charset=utf-8`);
            response.end(content);
        });
    }


});

但是,不行,我需要给 shell 脚本一个对输出流的响应,但是怎么做呢?

enter image description here

【问题讨论】:

  • 你可以试试node-cmd模块
  • 完美,非常感谢!!!
  • 我可以发表我的评论作为接受的答案吗?
  • 是的,当然,你帮帮我!

标签: node.js shell


【解决方案1】:

节点命令

 Simple commandline/terminal interface to allow you to run cli or
     bash style commands as if you were in the terminal.

异步运行命令,如果需要可以得到字符串的输出。

所以做一些这样的事情来解决你的问题

var cmd=require('node-cmd');

cmd.get(
    'pwd',
    function(data){
        console.log('the current working dir is : ',data)
    }
);

cmd.run('whoami');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-13
    • 1970-01-01
    • 1970-01-01
    • 2012-01-24
    • 2016-05-23
    • 1970-01-01
    • 2021-10-10
    • 2014-04-19
    相关资源
    最近更新 更多