Advanced Input/output
There are other ways for input/output in JavaScript besides prompt
and console.log
. Here are a few examples:
Reading from a file: You can read input from a file using the built-in
fs
module in Node.js. Here's an example:
const fs = require('fs');
// Read input from a file
fs.readFile('input.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
Writing to a file: You can write output to a file using the
fs
module as well. Here's an example:
const fs = require('fs');
// Write output to a file
fs.writeFile('output.txt', 'Hello, world!', (err) => {
if (err) throw err;
console.log('Output written to file!');
});
Using HTML forms: If you're working with JavaScript in a web environment, you can use HTML forms to get input from users and display output to them. Here's an example:
<!DOCTYPE html>
<html>
<head>
<title>Input/output example</title>
</head>
<body>
<form>
<label>Enter your name:</label>
<input type="text" id="nameInput">
<button type="button" onclick="sayHello()">Say hello</button>
</form>
<p id="output"></p>
<script>
function sayHello() {
const name = document.getElementById('nameInput').value;
document.getElementById('output').innerText = `Hello, ${name}!`;
}
</script>
</body>
</html>
This example uses an HTML form to get the user's name, and a JavaScript function to display a greeting message to them. The output is displayed in a <p>
element with the ID "output".
Last updated