Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute shell command in foreground from node.js

I'm working on a Node.js CLI script that, as part of its duties, will sometimes need to take a large block of input text from the user. Right now, I'm just using the very basic readline.prompt(). I'd like some better editing capabilities. Rather than reinvent the wheel, I figure I could just do as crontab -e or visudo do and have the script launch a text editor that writes data to a temporary file, and read from that file once it exits. I've tried some things from the child_process library, but they all launch applications in the background, and don't give them control of stdin or the cursor. In my case, I need an application like vim or nano to take up the entire console while running. Is there a way to do this, or am I out of luck?

Note: This is for an internal project that will run on a single machine and whose source will likely never see the light of day. Hackish workarounds are welcome, assuming there's not an existing package to do what I need.

like image 889
Dan Hlavenka Avatar asked Dec 08 '25 21:12

Dan Hlavenka


1 Answers

Have you set the stdio option of child_process.spawn to inherit?

This way, the child process will use same stdin and stdout as the top node process.

This code works for me (node v4.3.2):

'use strict';

var fs = require('fs');
var child_process = require('child_process');
var file = '/tmp/node-editor-test';

fs.writeFile(file, "Node Editor", function () {
  var child = child_process.spawn('vim', [file], {stdio: 'inherit'});

  child.on('close', function () {
    fs.readFile(file, 'utf8', function (err, text) {
      console.log('File content is now', text);
    });
  });
});
like image 180
m6k Avatar answered Dec 10 '25 12:12

m6k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!