Skip to content

consider a function input() like in python #57232

Description

@ganeshkbhat

What is the problem this feature will solve?

python has a simple implementation of process stdin ingestion. do you wish to consider my recommendation of having a input() function like in python? the implementations for node.js can be far more tedious and complicated.

the proposal fo:

input(textToPrint: string = "", stream: boolean = false, buffer: boolean = true)

example usage:
await input("input text: ")
await input()

// single line input function usage
example usage:
input("input text: ", false) // single line without text print
input("", false) // single line without any text print
input("input text: ", false, true) // buffer response
input("", false, false) // text response

// continuous input function usage
example usage:
input("input text: ", true) // single line without text print
input("", true) // single line without any text print
input("input text: ", true, true) // buffer response
input("", true, false) // text response

python code:

input()

node.js code : continues forever in input

1.

function input(text) {
    console.log(text);
    async function read(stream) {
       if (stdin.isTTY) { return result; }
       const chunks = [];
       for await (const chunk of stream) chunks.push(chunk); 
       return Buffer.concat(chunks).toString('utf8');
    }
    var stdintext = await read(process.stdin);
    return stdintext;
}

console.log(input("What is your name?"))

2.

function input(text) { 
    console.log(text);
    var stdintext = require("fs").readFileSync("/dev/stdin", "utf-8");
    return stdintext;
}

console.log(input("What is your name?"))

3.

function input(text) { 
    console.log(text);
    var stdintext = require("fs").readFileSync(0, "utf-8");
    return stdintext;
}

console.log(input("What is your name?"))

4.


function input(text) {
    console.log(text);
    return new Promise((resolve, reject) => {
        let input = '';
        process.stdin.setEncoding('utf8');

        process.stdin.on('readable', () => {
            let chunk;
            while ((chunk = process.stdin.read()) !== null) {
                input += chunk;
            }
        });

        process.stdin.on('end', () => {
            resolve(input);
        });

        process.stdin.on('error', (err) => {
            reject(err);
        });
    });
}

// Example usage:
input("Input Your Text (continuous):")
    .then((stdinData) => {
        console.log("Input from stdin:\n", stdinData);
        // You can process the data here if needed.
    })
    .catch((error) => {
        console.error("Error reading stdin:", error);
    });

One line input:

1.

function input(text) {
    console.log(text);
    return new Promise((resolve, reject) => {
        process.stdin.setEncoding('utf8');
        let line = '';

        process.stdin.on('readable', () => {
            let chunk;
            while ((chunk = process.stdin.read()) !== null) {
                for (let char of chunk) {
                    if (char === '\n') {
                        process.stdin.pause(); // Stop reading after newline
                        resolve(line);
                        return; // Exit the readable event
                    } else {
                        line += char;
                    }
                }
            }
        });

        process.stdin.on('end', () => {
            if (line.length > 0) {
                resolve(line);
            } else {
                reject("No input provided");
            }
        });

        process.stdin.on('error', (err) => {
            reject(err);
        });
    });
}

// Example usage:
input("Input Your Text (single line):")
    .then((line) => {
        // console.log("Input:", line);
        process.exit(0);
    })
    .catch((error) => {
        console.error("Error:", error);
        process.exit(1);
    });

2.

returns buffer and/ or text based on implementation


function input(text) {
    console.log(text)
    return new Promise((resolve, reject) => {
        let buffer = Buffer.alloc(0); // Initialize an empty buffer

        process.stdin.on('readable', () => {
            let chunk;
            while ((chunk = process.stdin.read()) !== null) {
                // Find the index of the first newline character
                const newlineIndex = chunk.indexOf('\n');

                if (newlineIndex !== -1) {
                    // Newline found, extract the line up to the newline
                    const lineBuffer = Buffer.concat([buffer, chunk.slice(0, newlineIndex)]);
                    process.stdin.pause(); // Stop reading
                    resolve(lineBuffer);
                    return; // Exit the readable event
                } else {
                    // No newline, append the chunk to the buffer
                    buffer = Buffer.concat([buffer, chunk]);
                }
            }
        });

        process.stdin.on('end', () => {
            if (buffer.length > 0) {
                resolve(buffer);
            } else {
                reject("No input received");
            }
        });

        process.stdin.on('error', (err) => {
            reject(err);
        });
    });
}

// Example usage:
input("Input Text")
    .then((buffer) => {
        console.log("Input (buffer):", buffer);
        console.log("Input (text):", buffer.toString('utf8')); // Convert to text
        process.exit(0);
    })
    .catch((error) => {
        console.error("Error:", error);
        process.exit(1);
    });

What is the feature you are proposing to solve the problem?

simply usage of command line for creating menus, creating simpler input, working with inputs easily alongside the current process.stdin

What alternatives have you considered?

none. use an external package

Activity

  1. marco-ippolito commented on Feb 28, 2025

    @marco-ippolito
    Member
  2. aduh95 commented on Mar 2, 2025

    @aduh95
    Contributor

    For example, you can do

    import { createInterface } from 'node:readline/promises';
    import { stdin, stdout } from 'node:process';
    const rl = createInterface({
      input: stdin,
      output: stdout,
    });
    const input = rl.question.bind(rl);
    
    const response = await input('How are you doing today? ', { signal: AbortSignal.timeout(10_000) });
    console.log({ response });
    rl.close();
  3. github-actions commented on Aug 30, 2025

    @github-actions
    Contributor

    There has been no activity on this feature request for 5 months. To help maintain relevant open issues, please add the never-stale Issues and PRs exempt from automated stale handling. label or close this issue if it should be closed. If not, the issue will be automatically closed 6 months after the last non-automated comment.
    For more information on how the project manages feature requests, please consult the feature request management document.

  4. added
    staleIssues and PRs marked stale due to inactivity and scheduled for automatic closure.
    on Aug 30, 2025
  5. github-actions commented on Sep 29, 2025

    @github-actions
    Contributor

    There has been no activity on this feature request and it is being closed. If you feel closing this issue is not the right thing to do, please leave a comment.

    For more information on how the project manages feature requests, please consult the feature request management document.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature requestIssues requesting new Node.js features.staleIssues and PRs marked stale due to inactivity and scheduled for automatic closure.

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions