Home > Web Front-end > JS Tutorial > How Can I Read and Write Files Using JavaScript on Both Server and Client Sides?

How Can I Read and Write Files Using JavaScript on Both Server and Client Sides?

Patricia Arquette
Release: 2024-12-01 02:33:10
Original
458 people have browsed it

How Can I Read and Write Files Using JavaScript on Both Server and Client Sides?

Reading and Writing to Files with JavaScript

In most cases, accessing local files is not permitted in client-side JavaScript due to security constraints. However, in server-side JavaScript environments, such as Node.js, file manipulation is possible through the File class.

Server-Side JavaScript (Node.js):

Node.js offers the FileSystem class, allowing you to:

// Reading Example
const fs = require('fs');
fs.readFile('file.txt', 'utf-8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

// Writing Example
fs.writeFile('output.txt', 'Hello World!', (err) => {
  if (err) throw err;
  console.log('File written successfully.');
});
Copy after login

HTML5 (Client-Side, Experimental):

HTML5 provides experimental support for client-side file access through the File and FileReader objects. This allows you to:

// Reading Example
const file = document.querySelector('input[type=file]');
file.addEventListener('change', (e) => {
  const reader = new FileReader();
  reader.onload = () => {
    const data = reader.result;
    // Process file data
  };
  reader.readAsText(e.target.files[0]);
});

// Writing Example
const blob = new Blob(['Hello World!'], { type: 'text/plain' });
const fileUrl = URL.createObjectURL(blob);
const a = document.querySelector('a');
a.href = fileUrl;
a.download = 'output.txt';
a.click();
Copy after login

Note: Client-side file access is still evolving and may not be supported in all browsers or platforms.

The above is the detailed content of How Can I Read and Write Files Using JavaScript on Both Server and Client Sides?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template