Coding ยท ยท

Input and output (I/O) in JavaScript

Programming can be seen as taking inputs, doing something with them, then providing some kind of output. Inputs and outputs are also known as I/O (pronounced "eye-oh").

We've already seen that we can output to the command line with console.log('Hello'). Now we'll look at how to take input from a user, and how to use files as input and output.

Command line I/O

Use prompt() for text input and console.log() for output.

let num = prompt('Choose a number') // input
console.log(`You chose ${num} as your number`) // output

You can also ask a Boolean (ie true/false or yes/no) question to a user with confirm():

let like = confirm('Do you like ants?')
console.log(`You ${ like ? "do" : "don't" } like ants`)

When using prompt() for text input, you get a string back, even if someone inputs a number:

let num = prompt('Enter any integer') // user types 5.5
console.log(2 + num) // outputs: 25.5
console.log(2 + Number(num)) // outputs: 7.5
console.log(2 + parseInt(num)) // outputs: 7

... you can wrap user input in Number() to coerce it into a number which you can then do maths on. To coerce it to an integer (as opposed to a fractional number such as 5.5 above), use parseInt().

Input: reading a file

Run echo "this is in my file" > text.txt to create a text file called 'text.txt' with contents 'this is in my file'.

You can read this file with Bun.file():

let text = await Bun.file('text.txt').text()
console.log(`The file has this in it: ${text}`)

Note the keyword await above. This is often required when dealing with I/O, and if you forget to use it you'll see a message about a 'Promise'. What's happening here is the function is returning something called a 'promise', which you wait to 'resolve' until you can continue.

Notice also that this is Bun's specific implementation of reading a file, hence why Bun.file() starts with the word Bun. Node.js, Deno and web browsers have different ways of opening and reading files. Some languages require you to open a file handler, read the file line by line, then close the file handler, like this pseudocode shows:

fh = file.open('text.txt', 'read-only')
while (lines in fh)
  print fh.readLine()
fh.close()

Output: writing to a file

Bun has an easy way to write strings to files too:

let text = 'The quick brown fox.'
await Bun.write('output.txt', text)

If you run the above code it may seem like nothing has happened. On the command line, run ls in your folder though and you'll see a file called 'output.txt'. Inspect the contents of that file with cat output.txt and you should see the text string inside it.

Notice again how we use the await keyword, as we often have to when dealing with I/O.