Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to manipulate files using JS

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to use JS operation file", the article explains the content is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "how to use JS operation file" bar!

JS reads the file FileReader

The FileReader object allows Web applications to asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the files or data to read.

Document

FileReader

Events and methods

Event handling

FileReader.onabort handles the abort event. This event is triggered when the read operation is interrupted. FileReader.onerror handles the error event. This event is triggered when an error occurs in the read operation. FileReader.onload handles the load event. This event is triggered when the read operation is complete. FileReader.onloadstart handles the loadstart event. This event is triggered when the read operation starts. FileReader.onloadend handles the loadend event. This event is triggered at the end of the read operation (either successful or failed). FileReader.onprogress handles the error event. This event is triggered when an error occurs in the read operation.

Standard method

FileReader.abort ()

Aborts the read operation. When returned, the readyState property is DONE.

FileReader.readAsArrayBuffer ()

Start reading the contents of the specified Blob. Once finished, the result property will store the ArrayBuffer data object of the file being read.

FileReader.readAsDataURL ()

Starts reading the contents of the specified Blob. Once done, the result attribute contains a string in the format data: URL to represent the contents of the file being read.

FileReader.readAsText ()

Starts reading the contents of the specified Blob. Once done, the result property contains a string to represent the contents of the file being read.

Basic use

File preparation read.txt (you can read computer files at will)

HTML structure

JS call

_ 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 plain text of the result) reader.readAsText (this.files [0]) / / read the result successfully: the file (read.txt on the computer) reader.onload = function () {/ / after the reading is completed The data is saved in the result property of the object console.log (this.result) / / print: the file has been read successfully}})}

JS calls use other methods (as do other methods)

ReadAsDataURL

_ window.onload = function () {var inpFile = document.querySelector ('input [type = file]') inpFile.addEventListener ('change' Function () {var reader = new FileReader () / / use readAsDataURL (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 html and file above-or prepare a larger file; it 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 status" + this.readyState) console.log ("start loading")} reader.onloadend= function () {console .log ("onloadend status" + this.readyState) console.log ("loading end")} reader.onprogress = function () {count++ Console.log ("onprogress status" + this.readyState) console.log ("loading" + count)} reader.onload = function () {console.log ("data obtained by onload" + this.result) Console.log ("status" + this.readyState)} reader.onerror = function () {console.log ('error')} reader.onerror = function () { Console.log ('handles the abort event. This event is triggered when the read operation is interrupted.') })}

The results are as follows

Analysis of important results:

Status 1 (readyState): data is being loaded

Status 2: all read requests have been completed.

Of course, a status of 0 (readyState) indicates that no data has been loaded.

Every time you pass 50ms or so, a progress event is triggered; that is, this may be triggered multiple times, and the onload event is triggered before the onloadend.

The error event is triggered when the file cannot be read for a variety of reasons. When the error event is triggered, the relevant information is stored in the error property of the FileReader object, which stores an object with only one property code, the error code. 1 indicates no file found, 2 indicates security error, 3 indicates read interrupt, 4 indicates unreadable file, and 5 indicates encoding error.

If you want to interrupt the reading process, you can call the abort method, which triggers the abort event. When returned, the readyState property is DONE. It is generally used for background operations.

Node operation file (readfile)

According to the above, the JavaScript in the browser does not have the ability to manipulate files (based on security, you cannot directly manipulate local files), but the JavaScript in Node has the ability to manipulate files.

How to read files by node (you can ignore the code when installing node)

First of all, install the node environment (very simple, a lot of tutorials online), preferably nodemon, too.

Open your cmd, or you can use git

Create a JS file

Load the core module of node

Use readFile

Enter the node file name. js in cmd

/ / 1. Load the fs core module var fs = require ('fs') / / 2 using the require method. 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 has no data / / error error object fs.readFile ('read.txt', function (error) Data) {/ / here you can confirm whether an error has occurred by judging error. If (error) {console.log ('failed to read the file')} else {console.log (data.toString ())}))

Result

File reading is an asynchronous operation

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

Use Promisevar 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)}) file fs.writeFile ('read.txt') Hello, everyone To introduce you, I am file writing', function (error) {if (error) {console.log ('write failed')} else {console.log ('write successful')}) Thank you for reading. This is the content of "how to use JS to manipulate files". After the study of this article, I believe you have a deeper understanding of how to use JS to manipulate files. The specific use situation still needs to be verified by practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report