JavaScript:
Читання текстового файлу

How to: (Як зробити:)

Use fetch for web files, FileReader for client-side operations, or fs in Node.js. Here’s the quick code.

// Web files:
fetch('data.txt')
  .then(response => response.text())
  .then(text => console.log(text));

// Client-side files:
document.getElementById('input-file').addEventListener('change', event => {
  const file = event.target.files[0];
  const reader = new FileReader();
  reader.onload = e => console.log(e.target.result);
  reader.readAsText(file);
});

// Node.js:
const fs = require('fs');

fs.readFile('data.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

Sample Output for each:

Hello, this is a text file content!

Deep Dive (Поглиблене занурення):

Historically, JavaScript was browser-only; Node.js allowed server-side file operations. Alternatives include XMLHttpRequest for browsers (but fetch is modern). Implementation details matter: know when to use asynchronous (fs.readFile) versus synchronous (fs.readFileSync) for Node.js, or how to handle file reading in chunks for big files.

See Also (Дивіться також):