Use JS to operate files (FileReader reads --node's fs)

Use JS to operate files (FileReader reads --node's fs)

JS reads file FileReader

The FileReader object allows a Web application to asynchronously read the contents of a file (or raw data buffer) stored on the user's computer, using a File or Blob object to specify the file or data to read.

document

FileReader

Events and methods

Event Handling

FileReader.onabort Handle the abort event. This event is triggered when a read operation is interrupted.
FileReader.onerror Handle the error event. This event is triggered when an error occurs during a read operation.
FileReader.onload Handle the load event. This event is fired when a read operation is completed.
FileReader.onloadstart Handle the loadstart event. This event is fired when a read operation starts.
FileReader.onloadend Handle the loadend event. This event is emitted when a read operation completes (either successfully or unsuccessfully).
FileReader.onprogress Handle the error event. This event is triggered when an error occurs during a read operation.

Standard Methods

  • FileReader.abort()

Abort the read operation. On return, the readyState property is DONE.

  • FileReader.readAsArrayBuffer()

Start reading the contents of the specified Blob. Once completed, the result property will contain the ArrayBuffer data object of the read file.

  • FileReader.readAsDataURL()

Start reading the contents of the specified Blob. Once completed, the result property will contain a string in the format of a data: URL representing the contents of the file read.

  • FileReader.readAsText()

Start reading the contents of the specified Blob. Once completed, the result property will contain a string representing the contents of the file read.

Basic Use

File preparation: read.txt (you can read any file on your computer)

Reading files

HTML Structure

<input type="file" multiple>

JS call

<script>
	window.onload = function(){
		var inpFile = document.querySelector('input[type=file]')
		inpFile.addEventListener('change', function(){
			var reader = new FileReader()
			// Send asynchronous request // 0. Use the readAsText method (read the result as normal text)
			reader.readAsText(this.files[0]) 
			// Result of successful reading: The file has been read successfully (the file read.txt on the computer)
			reader.onload = function(){
    		//After reading, the data is saved in the result property of the object console.log(this.result)//Print: The file has been read successfully }
		})
	}
</script>

JS calls use other methods (other methods are used in the same way)

readAsDataURL

window.onload = function(){
		var inpFile = document.querySelector('input[type=file]')
		inpFile.addEventListener('change', function(){
			var reader = new FileReader()
			// Use readAsDataURL (to get base64 encoding)
			reader.readAsDataURL(this.files[0])
			reader.onload = function(){
    		console.log(this.result)
    		//data:text/plain;base64,5bey57uP5oiQ5Yqf6K+75Y+W5paH5Lu2
  			}
		})
	}

Event Handling

JS call (still use the above HTML and files – or prepare a larger file; the effect will be better)

window.onload = function(){
		var inpFile = document.querySelector('input[type=file]')
		inpFile.addEventListener('change', function(){
			var reader = new FileReader()
			reader.readAsText(this.files[0])
			var count = 0;
			reader.onloadstart = function(){
				console.log("onloadstart state"+this.readyState)
    			console.log("Start loading")
  			}
  			reader.onloadend = function(){
  				console.log("onloadend state"+this.readyState)
    			console.log("Loading completed")
  			}
  			reader.onprogress = function(){
  				count++;
  				console.log("onprogress state"+this.readyState)
    			console.log("Loading"+count)
  			}
			reader.onload = function(){
    			console.log("The data obtained by onload is "+this.result)
    			console.log("status"+this.readyState)
  			}
  			reader.onerror = function(){
    			console.log('something went wrong')
  			}
  			reader.onerror = function(){
    			console.log('Handle the abort event. This event is triggered when the read operation is interrupted.')
  			}
		})
	}

The results are as follows

The result of event processing

Important results analysis:

  • State 1 (readyState): Data is being loaded
  • Status 2: All read requests have been completed.
  • Of course, the state of 0 (readyState) means that no data has been loaded yet.
  • A progress event is triggered every 50ms or so; that is, it may be triggered multiple times, and the onload event is triggered before the onloadend event.
  • When the file cannot be read for various reasons, the error event will be triggered. When the error event is triggered, the relevant information is saved in the error property of the FileReader object. This property will save an object with only one property code, which is the error code. 1 means file not found, 2 means security error, 3 means read interrupted, 4 means file unreadable, and 5 means encoding error.
  • If you want to interrupt the reading process, you can call the abort method, which will trigger the abort event. On return, the readyState property is DONE. Generally used for background operations.

Node operation file (readfile)

Based on the above, we can see that JavaScript in the browser does not have the ability to operate files (based on security, it cannot directly operate local files), but JavaScript in Node has the ability to operate files.

How does node read files? (You can ignore the code when installing node)

  • First, you need to install the node environment (very simple, there are many tutorials online), and it is best to also install nodemon
  • Open your cmd and use git
  • Create JS file
  • Loading the core module of node
  • Using readFile
  • Enter node file name.js in cmd
// 1. Use the require method to load the fs core module var fs = require('fs')
// 2. Read file // The first parameter is the file path to be read // The second parameter is a callback function // Success // data data // error null
// Failed // data undefined no data // error error object fs.readFile('read.txt', function (error, data) {
  // Here you can check if an error occurs by judging error if (error) {
    console.log('Failed to read the file')
  } else {
    console.log(data.toString())
  }
})

result

Node reads the file

File reading is an asynchronous operation

When we read multiple files, we find that using readfile to read files does not necessarily print the results in order, so this is an asynchronous operation. How to read files sequentially.

Using Promises

var fs = require('fs')
function pReadFile(filePath) {
  return new Promise(function (resolve, reject) {
    fs.readFile(filePath, 'utf8', function (err, data) {
      if (err) {
        reject(err)
      } else {
        resolve(data)
      }
    })
  })
}
pReadFile('./data/a.txt')
  .then(function (data) {
    console.log(data)
    return pReadFile('./data/b.txt')
  })
  .then(function (data) {
    console.log(data)
    return pReadFile('./data/c.txt')
  })
  .then(function (data) {
    console.log(data)
  })

Writing files

fs.writeFile('read.txt', 'Hello everyone, let me introduce myself to you. I am a file writer.', function (error) {
  if (error) {
    console.log('Write failed')
  } else {
    console.log('Written successfully')
  }
})

The above is my personal experience. I hope it can give you a reference. I also hope that you will support 123WORDPRESS.COM.

You may also be interested in:
  • JS+HTML5 FileReader object usage example
  • JavaScript html5 uses FileReader to implement upload function
  • JavaScript reads files through the filereader interface

<<:  Table of CSS Bugs Caused by hasLayout

>>:  Implementation of CSS child element selection parent element

Recommend

A Brief Analysis of Subqueries and Advanced Applications in MySql Database

Subquery in MySql database: Subquery: nesting ano...

Detailed tutorial on installing MySQL 8.0.19 in zip version on win10

Table of contents 1. After downloading, unzip it ...

Introduction to Linux environment variables and process address space

Table of contents Linux environment variables and...

How to use CSS style to vertically center the font in the table

The method of using CSS style to vertically cente...

Detailed installation process of nodejs management tool nvm

nvm nvm is responsible for managing multiple vers...

Detailed explanation of JavaScript onblur and onfocus events

In HTML pages, visual elements such as buttons an...

The process of SSH service based on key authentication in Linux system

As we all know, SSH is currently the most reliabl...

JavaScript to achieve the effect of clicking on the self-made menu

This article shares the specific code of JavaScri...

In-depth understanding of the use of CSS clear:both

clear:both is used to清除浮動This is the impression I...

Implementation code of Nginx anti-hotlink and optimization in Linux

Hide version number The version number is not hid...

An article teaches you JS function inheritance

Table of contents 1. Introduction: 2. Prototype c...

What you need to know about MySQL auto-increment ID

Introduction: When using MySQL to create a table,...

A brief discussion on tags in HTML

0. What is a tag? XML/HTML CodeCopy content to cl...