node.js: readSync from stdin?

前端 未结 11 1569
北海茫月
北海茫月 2020-12-08 01:48

Is it possible to synchronously read from stdin in node.js? Because I\'m writing a brainfuck to JavaScript compiler in JavaScript (just for fun). Brainfuck supports a read o

11条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-08 02:27

    An updated version of Marcus Pope's answer that works as of node.js v0.10.4:

    Please note:

    • In general, node's stream interfaces are still in flux (pun half-intended) and are still classified as 2 - Unstable as of node.js v0.10.4.
    • Different platforms behave slightly differently; I've looked at OS X 10.8.3 and Windows 7: the major difference is: synchronously reading interactive stdin input (by typing into the terminal line by line) only works on Windows 7.

    Here's the updated code, reading synchronously from stdin in 256-byte chunks until no more input is available:

    var fs = require('fs');
    var BUFSIZE=256;
    var buf = new Buffer(BUFSIZE);
    var bytesRead;
    
    while (true) { // Loop as long as stdin input is available.
        bytesRead = 0;
        try {
            bytesRead = fs.readSync(process.stdin.fd, buf, 0, BUFSIZE);
        } catch (e) {
            if (e.code === 'EAGAIN') { // 'resource temporarily unavailable'
                // Happens on OS X 10.8.3 (not Windows 7!), if there's no
                // stdin input - typically when invoking a script without any
                // input (for interactive stdin input).
                // If you were to just continue, you'd create a tight loop.
                throw 'ERROR: interactive stdin input not supported.';
            } else if (e.code === 'EOF') {
                // Happens on Windows 7, but not OS X 10.8.3:
                // simply signals the end of *piped* stdin input.
                break;          
            }
            throw e; // unexpected exception
        }
        if (bytesRead === 0) {
            // No more stdin input available.
            // OS X 10.8.3: regardless of input method, this is how the end 
            //   of input is signaled.
            // Windows 7: this is how the end of input is signaled for
            //   *interactive* stdin input.
            break;
        }
        // Process the chunk read.
        console.log('Bytes read: %s; content:\n%s', bytesRead, buf.toString(null, 0, bytesRead));
    }
    

提交回复
热议问题