Terminal applications use Standard I/O, frequently notated as stdio
, to read and write text to the terminal. For those who are new to working with consoles, stdio
typically consists of three streams: stdin
, stdout
, and stderr
.
Output text with stdout
“Standard out” is where a program writes its output. In ruby, when you run puts
, it implicitly writes to $stdout.puts
, which displays text in the users terminal.
Terminalwire replaces $stdout.puts
in Thor with Terminalwire::Server::Resource::STDOUT#puts
to stream output over WebSockets to the client. This allows you to write to the terminal as you would in a normal terminal application.
# Print "Hello, World!" to the terminal and append a newline puts "Hello, World!" # Print "Hi!" to the terminal without a newline print "Hi!"
Read text stdin
“Standard in” is where a program reads its input. In ruby, when you run gets
, it implicitly reads from $stdin.gets
, which reads text from the users terminal.
print "What is your name?: " # Read a line of text from the terminal name = gets.chomp # chomp removes the newline character # Print a greeting to the terminal puts "Hello, #{name}!"
Reading passwords via getpass
When you need to read a password from the terminal, you can use the getpass
method in Thor. This method will prompt the user for a password and return the value as a string without showing the users input on their terminal. This prevents people from seeing the password as it is typed.
puts "Login to your account" # Read a line of text from the terminal password = getpass # chomp removes the newline character # Check if the password is correct. if password == "password" puts "You are logged in" else puts "Incorrect password" end
Display error message with stderr
“Standard error” is where a program writes its error messages. In ruby, when you run warn
, it implicitly writes to $stderr.puts
, which displays text in the users terminal.
# Write an error message to the users terminal warn "Oops, An error occurred"