Home >Web Front-end >JS Tutorial >Can JavaScript Read and Write Files?

Can JavaScript Read and Write Files?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-03 10:56:13175browse

Can JavaScript Read and Write Files?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn