Home  >  Article  >  Web Front-end  >  Take you to learn the File API, Streams API and Web Cryptography API in JavaScript

Take you to learn the File API, Streams API and Web Cryptography API in JavaScript

WBOY
WBOYforward
2022-04-01 11:53:013182browse

This article brings you relevant knowledge about javascript, which mainly introduces the relevant content of File API, Streams API, and Web Cryptography API in JavaScript. I hope it will be helpful to everyone.

Take you to learn the File API, Streams API and Web Cryptography API in JavaScript

[Related recommendations: javascript video tutorial]

1. Atomics and SharedArrayBuffer

Multiple context access SharedArrayBuffer, if operations are performed on the buffer at the same time, resource contention problems may occur. The Atomics API allows multiple contexts to safely read and write a SharedArrayBuffer by forcing that only one operation can be performed on the buffer at a time.
The nature of atomic operations precludes optimizations (such as instruction reordering) that the operating system or computer hardware would normally perform automatically. Atomic operations also make it impossible to access memory concurrently. If used improperly, it may cause program execution to slow down. For this reason, the original design intention of the Atomics API is to build complex multi-threaded JavaScript programs based on minimal but stable atomic behavior. .

2. Basics of atomic operations

1. Arithmetic and bit operation methods

Atomics API provides a set of simple methods for executing in-place operations Modify operations. In the ECMA specification, these methods are defined as AtomicReadModifyWrite operations. Under the hood, these methods read a value from a location in the SharedArrayBuffer, perform arithmetic and bitwise operations, and finally write the result to the same location. The atomic nature of these operations means that the read, modify, and write back operations described above will be executed in order and will not be interrupted by other threads.

//创建大小为1的缓冲区let sharedArrayBuffer = new SharedArrayBuffer(1);
//基于缓冲创建Unit8Arraylet typedArray = new Unit8Array(sharedArrayBuffer);
//所有ArrayBuffer全部初始化为0console.log(typedArray);
//Unit8Array[0]
//对索引0处的值执行原子加10Atomics.add(typedArray,0,10);
//Unit8Array[10]
//对索引0处的值执行原子减10Atomics.sub(typedArray,0,10);
//Unit8Array[0]

2. Atomic reading and writing

The browser's JavaScript compiler and the CPU architecture itself have the authority to rearrange instructions to improve program execution efficiency. Under normal circumstances, JavaScript's single-threaded environment can perform this optimization at any time, but instruction rearrangement in multi-threads may lead to resource contention and is extremely difficult to troubleshoot.
The Atomics API solves this problem in two main ways:

  • The order of all atomic instructions is never rearranged with respect to each other.

  • Using atomic reads or atomic writes ensures that all instructions are not reordered relative to atomic reads and writes.

In addition to reading and writing buffer values, Atomics.load() and Atomics.store() can also build "code fences". The JavaScript engine ensures that non-atomic instructions can be rearranged locally relative to load() and store(), but this rearrangement will not violate the boundaries of atomic reads and writes.

const sharedArrayBuffer = new SharedArrayBuffer(4);
const view = new Unit32Array(sharedArrayBuffer);
//执行非原子写view[0] = 1;
//非原子写可以保证在这个读操作之前完成,因此这里一定会读到1console.log(Atomics.load(view,0));
//1
//执行原子写Atomics.store(view,0,2);
//非原子读可以保证在原子写完成后发生,这里一定会读到2console.log(view[0]);
//2

3. Atomic exchange

In order to ensure continuous and uninterrupted reading first and then writing, the Atomics API provides two methods: exchange() and compareExchange() . Atomics.exchange() performs a simple exchange that guarantees that other threads will not interrupt the exchange.

const sharedArrayBuffer = new SharedArrayBuffer(4);
const view = new Unit32Array(sharedArrayBuffer);
//在索引0处写入10Atomics.store(view,0,10);
//从索引0处读取值,然后在索引0处写入5console.log(Atomics.exchange(view,0,5));
//10
//从索引0处读取值console.log(Atomics.load(view,0));
//5

In a multi-threaded program, a thread may only want to write to a shared buffer if no other thread has modified the value since the last time it was read. If the value has not been modified, this thread can safely write the updated value: if the value has been modified, performing a write operation will destroy the value calculated by other threads. For this kind of task, the Atomics API provides the compare-Exchange() method. This method only performs the write operation if the value at the target index matches the expected value.

4. Atomic Futex operation and locking

Without some kind of locking mechanism, multi-threaded programs cannot support complex requirements. To this end, the Atomics API provides methods that mimic Linux Futex (fast user-space mutex). These methods, while very simple in themselves, can serve as basic components for more complex locking mechanisms.
All atomic Futex operations can only be used on Int32Array views, and can only be used inside worker threads.

3. Cross-context messaging

Cross-document messaging, sometimes also called ) the ability to transfer information between.

4. Encoding API

Encoding API is mainly used to convert between strings and stereotyped arrays.

5. File API and Blob API

1. File type

File API is still based on the file input field in the form, but adds The ability to directly access file information. HTML5 adds a files collection to the DOM for file input elements. When the user selects one or more files in the file field, the files collection will contain a set of File objects representing the selected files. Each File object has some read-only attributes.

2. FileReader type

The FileReader type represents an asynchronous file reading mechanism. You can think of FileReader as similar to XMLHttpRequest, except that it is used to read from the file system. Fetch the file instead of reading the data from the server. The FileReader type provides several methods for reading file data.

  • readAsText(file,encoding);//Read plain text content from the file and save it in the result attribute

  • readAsDataURL(file);//Read the file and save the data URI of the content in the result attribute

  • readAsBinaryString(file);//Read Get the file and save the binary data of each character in the result attribute

  • readAsArrayBuffer(file);//Read the file and save the file content in the result attribute in the form of ArrayBuffer

3. FileReaderSync type

Synchronous version of FileReader type.

4. Blob and partial reading

In some cases, you may need to read part of the file instead of the entire file. For this purpose, the File object provides a name is the slice() method. The slice() method receives two parameters: the starting byte and the number of bytes in the Yaodu area. This method returns an instance of Blob, which is actually a superclass of File.
Blob represents a binary large object, which is JavaScript’s encapsulation type for unmodifiable binary data. Arrays containing strings, ArrayBuffers, ArrayBufferViews, and even other blobs can be used to create blobs. The Blob constructor can receive an options parameter and specify the MIME type in it.

6. Streams API

1. Application scenarios

Streams API was born to solve a simple but basic problem: Web How can applications consume small, ordered chunks of information instead of large chunks? There are two main application scenarios for this capability.

  1. Large chunks of data may not be available all at once. The response to a network request is a typical example. Network loads are delivered in continuous packets, and streaming allows applications to consume data as it arrives rather than having to wait until all the data has been loaded.
  2. Large pieces of data may need to be processed in small parts. Video processing, data compression, image encoding, and JSON parsing are all examples of things that can be processed in small pieces without having to wait until all the data is in memory.

2. Understanding streams

Streams API defines three streams:

  • Readable stream: can be read through a public interface Get a stream of data blocks. Data enters the stream internally from the underlying source and is then processed by the consumer.

  • Writable stream: A stream that can write data blocks through a certain public interface. The producer (consumer) writes data to the stream, and the data is transferred internally to the underlying data slot (sink).

  • Conversion stream: It consists of two streams, the writable stream is used to receive data, and the readable stream is used to output data. These two stream quality checks are transformers that can inspect and modify stream content as needed.

7. Web Cryptography API

The Web Cryptography API describes a set of cryptography tools that standardizes how JavaScript implements encryption in a secure and conventional manner. These tools include generating, using, and applying cryptographic key pairs, encrypting and decrypting information, and reliably generating random numbers.

When they need to generate random numbers, many people will use Math.random(). This method is implemented in the browser as a pseudo-random number generator (PRNG, PseudoRandom Number Generator). The so-called pseudo refers to the process of generating values ​​that is not truly random. The values ​​generated by PRNG only simulate random characteristics. The browser's PRNG does not use a true random source, but only applies a fixed algorithm to an internal state. Each time Math.random() is called, this internal state is modified by an algorithm, and the result is converted into a new random number. For example, the V8 engine uses an algorithm called xorshift128 to perform this modification.

Since the algorithm itself is fixed and its input is only the previous state, the random number sequence is also determined. xorshift128 Uses 128-bit internal state, and the algorithm is designed so that any initial state will generate 2128-1 pseudo-random values ​​before repeating itself. This kind of loop is called a permutation loop, and the length of this loop is called a period. It is obvious that if the attacker knows the internal state of the PRNG, he can predict the subsequently generated pseudo-random values. If the developer inadvertently uses PRNG to generate a private key for encryption, the attacker can use this feature of PRNG to calculate the private key.

Pseudo-random number generator is mainly used to quickly calculate seemingly random numbers, but it is not suitable for encryption algorithms. To solve this problem, cryptographically secure pseudo-random number generator (CSPRNG, Cryptographically Secure PseudoRandom Number Generator), adds an additional entropy as input, such as testing hardware time or other system characteristics with unpredictable behavior. Although it is not as fast as PRNG, the generated value is more difficult to predict and can be used for encryption.

The Web Cryptography API introduces CSPRNG, which can be accessed on the global Crypto object through crypto.getRandomValues(). Unlike Math.random() which returns a floating point number between 0 and 1, getRandomValues() will write random values ​​into the stereotyped array passed to it as a parameter. The class of the stereotyped array does not matter because the underlying buffer will be filled with random bits.

JavaScript Mind Map

Take you to learn the File API, Streams API and Web Cryptography API in JavaScript

[Related recommendations: javascript video tutorial, web front-end]

The above is the detailed content of Take you to learn the File API, Streams API and Web Cryptography API in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete