This works great for me:

const { spawn } = require('child_process')
const shell = spawn('sh',[], { stdio: 'inherit' })
shell.on('close',(code)=>{console.log('[shell] terminated :',code)})
Answer from Adam on Stack Overflow
Top answer
1 of 3
28

This works great for me:

const { spawn } = require('child_process')
const shell = spawn('sh',[], { stdio: 'inherit' })
shell.on('close',(code)=>{console.log('[shell] terminated :',code)})
2 of 3
11

First and foremost, one of the things preventing node from interfacing with other interactive shells is that the child application must keep its "interactive" behavior, even when stdin doesn't look like a terminal. python here knew that its stdin wasn't a terminal, so it refused to work. This can be overridden by adding the -i flag to the python command.

Second, as you well mentioned in the update, you forgot to write a new line character to the stream, so the program behaved as if the user didn't press Enter. Yes, this is the right way to go, but the lack of an interactive mode prevented you from retrieving any results.

Here's something you can do to send multiple inputs to the interactive shell, while still being able to retrieve each result one by one. This code will be resistant to lengthy outputs, accumulating them until a full line is received before performing another instruction. Multiple instructions can be performed at a time as well, which may be preferable if they don't depend on the parent process' state. Feel free to experiment with other asynchronous structures to fulfil your goal.

var cp = require('child_process');
var childProcess = cp.spawn('python', ['-i']);

childProcess.stdout.setEncoding('utf8')

var k = 0;
var data_line = '';

childProcess.stdout.on("data", function(data) {
  data_line += data;
  if (data_line[data_line.length-1] == '\n') {
    // we've got new data (assuming each individual output ends with '\n')
    var res = parseFloat(data_line);
    data_line = ''; // reset the line of data

    console.log('Result #', k, ': ', res);

    k++;
    // do something else now
    if (k < 5) {
      // double the previous result
      childProcess.stdin.write('2 * + ' + res + '\n');
    } else {
      // that's enough
      childProcess.stdin.end();
    }
  }
});


childProcess.stdin.write('1 + 0\n');
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-use-the-node-js-repl
How To Use the Node.js REPL | DigitalOcean
March 18, 2022 - The Node.js Read-Eval-Print-Loop (REPL) is an interactive shell that processes Node.js expressions. The shell reads JavaScript code the user enters, evaluate…
🌐
Opensource.com
opensource.com › article › 18 › 7 › node-js-interactive-cli
Build an interactive CLI with Node.js | Opensource.com
#!/usr/bin/env node const inquirer = require("inquirer"); const chalk = require("chalk"); const figlet = require("figlet"); const shell = require("shelljs"); const init = () => { console.log( chalk.green( figlet.textSync("Node JS CLI", { font: "Ghost", horizontalLayout: "default", verticalLayout: "default" }) ) ); }; const askQuestions = () => { const questions = [ { name: "FILENAME", type: "input", message: "What is the name of the file without extension?"
🌐
GitHub
github.com › mrvisser › node-corporal
GitHub - mrvisser/node-corporal: An extensible interactive shell utility for Node.js
An extensible interactive shell utility for Node.js - mrvisser/node-corporal
Starred by 15 users
Forked by 8 users
Languages   JavaScript
🌐
davd.io
davd.io › nodejs-interactive-shell-with-hot-reload
NodeJS: Interactive shell with hot reload - davd.io
All exposed context variables will be available inside the shell. Then I run my appInitializer that will take care of all the route and database setup. Additionally, I’ve pulled in gaze, which allows to watch for changes in the filesystem recursively based on a glob expression. Whenever the watcher is triggered, it will call reloadModules(), which will invalidate Node’s require cache, load all the modules again and push it to the context object.
🌐
Google Groups
groups.google.com › g › nodejs › c › b9JdFrJQqn0
How can I run an interactive shell command?
Perhaps piping would do it for you : http://nodejs.org/docs/v0.6.0/api/all.html#child.stdin for example. ... Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message ... function shell() { process.stdin.pause(); require('tty').setRawMode(false); var ch = require('child_process').spawn('/bin/bash', [], { customFds: [0, 1, 2]}); ch.on('exit', function(){require('tty').setRawMode(true); process.stdin.resume()}); } shell();
🌐
GitHub
github.com › danielgtaylor › nesh
GitHub - danielgtaylor/nesh: An enhanced, extensible interactive shell for Node.js and CoffeeScript
An enhanced, extensible interactive shell for Node.js and CoffeeScript - danielgtaylor/nesh
Starred by 285 users
Forked by 27 users
Languages   CoffeeScript 99.9% | JavaScript 0.1%
Find elsewhere
🌐
Smashing Magazine
smashingmagazine.com › 2017 › 03 › interactive-command-line-application-node-js
How To Develop An Interactive Command Line Application Using Node.js — Smashing Magazine
You can simply use process.argv to read them. However, parsing their values and options is a cumbersome task. So, instead of reinventing the wheel, we will use the Commander module. Commander is an open-source Node.js module that helps you write interactive command line tools.
🌐
O'Reilly
oreilly.com › library › view › learning-node-2nd › 9781491943113 › ch04.html
Interactive Node with REPL and More on the Console - Learning Node, 2nd Edition [Book]
While you’re exploring the use ... Node to test your code. Node also comes with an interactive component known as REPL, or read-eval-print loop....
🌐
GitHub
gist.github.com › roccomuso › 9e7328d855ec97e0226e6e8cb036b09a
SSH Interactive shell session in Node.js · GitHub
SSH Interactive shell session in Node.js. GitHub Gist: instantly share code, notes, and snippets.
🌐
DEV Community
dev.to › sandeepmenon › interactive-node-js-command-line-54c1
Interactive Node JS command line - DEV Community
January 1, 2024 - In this step-by-step guide we will learn how to create an interactive nodejs command line application which fetches quote of the day, displays the result in fancy ASCII art, asks user whether they want to save the quote by writing to the file system.
🌐
W3Schools
w3schools.com › nodejs › nodejs_command_line.asp
Node.js Command Line Usage
The Node.js REPL (Read-Eval-Print Loop) is an interactive shell for executing JavaScript code.
🌐
Medium
medium.com › skilllane › build-an-interactive-cli-application-with-node-js-commander-inquirer-and-mongoose-76dc76c726b6
Build an interactive CLI application with Node.js, Commander, Inquirer, and Mongoose | by Chatthana Janethanakarn | SkillLane | Medium
January 8, 2019 - I personally prefer interactive input to the option parameters because it is more interactive. That’s how Inquirer module comes into play. We are going to need firstname, lastname, age, and email of the user while the password will be randomly generated. I name the sub-command “user:add” so we can define it using the command() method. ... Don’t forget to add the shebang line on the topmost of the file so that we can run the command directly using the interpreter of our choice. In this case we use node.
🌐
egghead.io
egghead.io › lessons › node-js-use-the-node-js-repl-shell
Use the Node.js REPL shell | egghead.io
In this lesson, you will learn how to use the interactive Node.js REPL (Read - Evaluate - Print - Loop) shell. The REPL shell allows you to enter javascript directly into a shell prompt and have the results evaluated by the node.js engine immediately. This is extremely useful for testing, debugging, or experimenting with new features to understand how they work.
Published   April 19, 2015
🌐
npm
npmjs.com › package › interactive-console
interactive-console - npm
simple fast utf-8 console/shell. Latest version: 0.0.5, last published: 8 years ago. Start using interactive-console in your project by running `npm i interactive-console`. There are no other projects in the npm registry using interactive-console.
      » npm install interactive-console
    
Published   Aug 08, 2017
Version   0.0.5
Author   Soldy
🌐
GitHub
github.com › dthree › vorpal
GitHub - dthree/vorpal: Node's framework for interactive CLIs
Inspired by and based on commander.js, Vorpal is a framework for building immersive CLI applications built on an interactive prompt provided by inquirer.js. Vorpal launches Node into an isolated CLI environment and provides a suite of API commands and functionality including:
Starred by 5.6K users
Forked by 281 users
Languages   JavaScript
🌐
CodeBurst
codeburst.io › building-a-node-js-interactive-cli-3cb80ed76c86
Building a Node JS interactive CLI | by Hugo Dias | codeburst
July 15, 2020 - inquirer — A collection of common interactive command line user interfaces · shelljs — Portable Unix shell commands for Node.js · Now create a index.js file with the following content: it’s always good to plan what a CLI needs to do before writing any code.
🌐
Node.js
nodejs.org › en › learn › command-line › how-to-use-the-nodejs-repl
Node.js — How to use the Node.js REPL
Node.js comes with a built-in REPL (Read-Eval-Print Loop) environment that allows you to execute JavaScript code interactively. The REPL is accessible through the terminal and is a great way to test out small pieces of code. The node command is the one we use to run our Node.js scripts: node script.js · ShellCopy to clipboard ·