Reading and Writing Files with JavaScript
Can it be done? It depends on the context. In most cases, using JavaScript to read and write files directly in a web browser is not feasible due to security and cross-origin restrictions. However, in server-side JavaScript environments, such as Node.js, file operations are possible.
Server-Side JavaScript
In Node.js, you can use the FileSystem module to manipulate files. Here's an example of reading and writing a file:
const fs = require('fs'); const data = 'Hello, world!'; fs.writeFileSync('file.txt', data); const fileData = fs.readFileSync('file.txt', 'utf8'); console.log(fileData);
Client-Side JavaScript
Recent updates to HTML5 have introduced capabilities for reading files from a user's device in certain scenarios. This is done using the FileReader object. However, it's important to note that this is still limited compared to server-side file operations.
const fileReader = new FileReader(); const inputFile = document.querySelector('input[type=file]'); inputFile.addEventListener('change', () => { const file = inputFile.files[0]; fileReader.readAsText(file); }); fileReader.onload = () => { console.log(fileReader.result); };
The above is the detailed content of Can JavaScript Read and Write Files?. For more information, please follow other related articles on the PHP Chinese website!