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

Nodejs global variables and global objects knowledge points and usage details

1. Global Object All modules can be called 1) glo...

Implementation of react loop data (list)

First, let's simulate the data coming from th...

Example code for implementing a text marquee with CSS3

Background Here's what happened, Luzhu accide...

Basic usage examples of Vue named slots

Preface Named slots are bound to elements using t...

Detailed example of MySQL joint table update data

1.MySQL UPDATE JOIN syntax In MySQL, you can use ...

How to Rename a Group of Files at Once on Linux

In Linux, we usually use the mv command to rename...

Website Color Schemes Choosing the Right Colors for Your Website

Does color influence website visitors? A few year...

React sample code to implement automatic browser refresh

Table of contents What is front-end routing? How ...

5 Tips for Protecting Your MySQL Data Warehouse

Aggregating data from various sources allows the ...

24 Practical JavaScript Development Tips

Table of contents 1. Initialize the array 2. Arra...

Implementation of select multiple data loading optimization in Element

Table of contents Scenario Code Implementation Su...

MySQL 5.7 generated column usage example analysis

This article uses examples to illustrate the usag...

Detailed discussion on the issue of mysqldump data export

1. An error (1064) is reported when using mysqldu...

Detailed explanation of replace into example in mysql

Detailed explanation of replace into example in m...

Detailed process of building mongodb and mysql with docker-compose

Let's take a look at the detailed method of b...