While it's generally not possible to perform file operations directly in a web browser, JavaScript offers capabilities for managing files on the server side through its Node.js implementation.
To read and write files using Node.js, utilize the fs (file system) module. Here's an example:
const fs = require('fs'); // Read a file fs.readFile('file.txt', 'utf8', (err, data) => { if (err) throw err; console.log(data); }); // Write a file fs.writeFile('file.txt', 'Hello world!', err => { if (err) throw err; console.log('File has been written successfully.'); });
With HTML5, you can access files from the client side:
const fileInput = document.getElementById('file-input'); fileInput.addEventListener('change', e => { const file = e.target.files[0]; // Read a file const reader = new FileReader(); reader.onload = () => { console.log(reader.result); }; reader.readAsText(file); // Write a file (client-side) const filename = 'file.txt'; const fileContent = 'Hello world!'; const blob = new Blob([fileContent], { type: 'text/plain' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = filename; a.click(); });
The above is the detailed content of How Can JavaScript Read and Write Files on Both the Server and Client Sides?. For more information, please follow other related articles on the PHP Chinese website!