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

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

Susan Sarandon
Release: 2024-12-01 03:48:13
Original
305 people have browsed it

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

Reading and Writing Files with JavaScript

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.

Server-Side File Manipulation

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.');
});
Copy after login

Client-Side File Manipulation

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();
});
Copy after login

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!

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