In JavaScript, reading and writing files primarily depends on the runtime environment. The approach to handling files differs between browser environments and Node.js environments.
1. Reading and Writing Files in Node.js
Node.js provides the fs module (File System module), which is an API for file operations. Using this module, we can conveniently read and write files.
Reading Files
javascript// Asynchronous reading fs.readFile('example.txt', 'utf8', (err, data) => { if (err) { console.error(err); return; } console.log(data); }); // Synchronous reading try { const data = fs.readFileSync('example.txt', 'utf8'); console.log(data); } catch (err) { console.error(err); }
Writing Files
javascriptconst fs = require('fs'); const content = 'This is new content.'; // Asynchronous writing fs.writeFile('example.txt', content, err => { if (err) { console.error(err); return; } console.log('File saved'); }); // Synchronous writing try { fs.writeFileSync('example.txt', content); console.log('File saved'); } catch (err) { console.error(err); }
2. Reading and Writing Files in the Browser
Due to browser security restrictions, directly reading and writing the file system from the browser is not allowed. However, we can achieve file reading and generation through user interactions.
Reading Files
In the browser, we can use the <input type="file"> element to allow users to select files and then use the FileReader API to read these files.
html<input type="file" id="fileInput">
javascriptconst input = document.getElementById('fileInput'); input.addEventListener('change', function() { const file = this.files[0]; const reader = new FileReader(); reader.onload = function() { console.log(reader.result); }; reader.readAsText(file); });
Writing Files
Although we cannot directly save files to the user's local storage in the browser, we can create a download link to allow users to download data generated by the webpage.
javascriptfunction download(content, filename, contentType) { const a = document.createElement('a'); const file = new Blob([content], {type: contentType}); a.href = URL.createObjectURL(file); a.download = filename; a.click(); URL.revokeObjectURL(a.href); } download('Hello world!', 'example.txt', 'text/plain');
The above describes methods for reading and writing files with JavaScript in different environments. In Node.js, we can directly access the file system, whereas in the browser, we need to indirectly handle files through user interactions.