Skip to content

Instantly share code, notes, and snippets.

@katanacrimson
Last active December 11, 2015 06:49
Show Gist options
  • Save katanacrimson/4562183 to your computer and use it in GitHub Desktop.
Save katanacrimson/4562183 to your computer and use it in GitHub Desktop.
Attempt at nodejs stdout "buffer interjection". Might be useful, ugly attempt though. Relies on ANSI escape codes (primarily SCP, RCP, ED). Suggestions welcome, cleanup even more welcome. Please note that some things were done for specific reasons however - overloading `process.stdout` methods was not possible in my attempts and resulted in erro…
var readline = require('readline'),
EventEmitter = require('events').EventEmitter,
buffer = require('buffer')
var stdoutBuffer = new EventEmitter() // can't use util.inherits() with process.stdout. :\
for(x in process.stdout) stdoutBuffer[x] = process.stdout[x]
stdoutBuffer.last = ''
stdoutBuffer.write = function(input, encoding) {
process.stdout.write(input, encoding)
var miniBuffer = input.toString().replace('\r', '')
miniBuffer = miniBuffer.split('\n')
if(miniBuffer.length > 1) {
stdoutBuffer.last = miniBuffer.pop()
} else {
stdoutBuffer.last += input.toString()
}
}
stdoutBuffer.interject = function(input, encoding) {
var last = this.last
process.stdout.write("\u001b[u\u001b[0J")
process.stdout.write(input, encoding)
process.stdout.write("\n")
process.stdout.write(last)
}
process.stdout.on('drain', function() { stdoutBuffer.emit('drain') })
process.stdout.on('error', function(error) { stdoutBuffer.writeable = false; stdoutBuffer.emit('error', error) })
process.stdout.on('close', function() { stdoutBuffer.writeable = false; stdoutBuffer.emit('close') })
rl = readline.createInterface({
input:process.stdin,
output:stdoutBuffer,
terminal: true,
})
rl
.on('line', function(line) {
stdoutBuffer.write("\u001b[s")
rl.prompt()
})
.on('close', function() {
process.exit(0)
})
stdoutBuffer.write("\u001b[s")
rl.prompt()
var i = 0
setInterval(function() {
stdoutBuffer.interject('test ' + ++i)
}, 10 * 1000)
@katanacrimson
Copy link
Author

Note: use within tmux seems to cause a minor bug - or tmux has a bug itself in cursor positioning. Unknown whether it affects screen.

@katanacrimson
Copy link
Author

@katanacrimson
Copy link
Author

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