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

What are File API, Streams API and Web Cryptography API in JavaScript

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Today, I would like to share with you the relevant knowledge of what File API, Streams API and Web Cryptography API are in JavaScript. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article.

1. Atomics and SharedArrayBuffer

When multiple contexts access the SharedArrayBuffer, resource contention problems may occur if operations are performed on the buffer at the same time. Atomics API allows multiple contexts to safely read and write a SharedArrayBuffer by forcing only one operation on the buffer at a time.

The nature of atomic operations excludes optimizations (such as instruction reordering) that the operating system or computer hardware usually performs automatically. Atomic operations also make it impossible to access memory concurrently, and if not applied properly, program execution may become slower. Therefore, Atomics API is originally designed to build complex multithreaded JavaScript programs on the basis of minimal but stable atomic behavior.

The basis of atomic operation 1, arithmetic and bit operation method

Atomics API provides a set of simple methods for performing in-place modification operations. In the ECMA specification, these methods are defined as AtomicReadModifyWrite operations. At the bottom, these methods read values from a location in the SharedArrayBuffer, perform arithmetic and bit operations, and finally write the results to the same location. The atomic nature of these operations means that the above read, modify, and write-back operations are performed sequentially and will not be interrupted by other threads.

/ / create a buffer of size 1 let sharedArrayBuffer = new SharedArrayBuffer (1); / / create Unit8Arraylet typedArray = new Unit8Array (sharedArrayBuffer) based on the buffer; / / initialize all ArrayBuffer to 0console.log (typedArray); / / Unit8Array [0] / / perform atomic plus 10Atomics.add (typedArray,0,10) for values at index 0; / / Unit8Array [10] / / perform atomic subtraction 10Atomics.sub (typedArray,0,10) for values at index 0; / / Unit8Array [0] 2, atomic read and write

Both the browser's JavaScript compiler and the CPU architecture itself have permission to rearrange instructions to improve program execution efficiency. Under normal circumstances, the single-threaded environment of JavaScript can be optimized at any time, but instruction rearrangement in multithreading can lead to resource contention and is extremely difficult to misarrange.

Atomics API solves this problem in two main ways:

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

Use atomic read or atomic write to ensure that all instructions are not reordered relative to atomic read and write.

In addition to the value of the read-write buffer, Atomics.load () and Atomics.store () can also build a "code fence". The JavaScript engine guarantees that non-atomic instructions can be rearranged locally relative to load () and store (), but this rearrangement does not violate atomic read-write boundaries.

Const sharedArrayBuffer = new SharedArrayBuffer (4); const view = new Unit32Array (sharedArrayBuffer); / / perform non-atomic write view [0] = 1 Atomics.store / non-atomic write is guaranteed to be completed before this read operation, so you must read 1console.log (Atomics.load (view,0)) here; / / 1 write / execute atomic write (view,0,2) / / non-atomic reading can guarantee that it will occur after atomic writing is completed. 2console.log (view [0]) must be read here. / / 23. Atomic exchange

To ensure continuous and continuous read-then-write, Atomics API provides two methods: exchange () and compareExchange (). Atomics.exchange () performs a simple swap to ensure that other threads are not interrupted and worth swapping.

Const sharedArrayBuffer = new SharedArrayBuffer (4); const view = new Unit32Array (sharedArrayBuffer); / / write 10Atomics.store (view,0,10) at index 0; / / read the value from index 0 and then write 5console.log (Atomics.exchange (view,0,5)) at index 0; / / 10 shock / read the value console.log (Atomics.load (view,0)) from index 0; / / 5

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

4. Atomic Futex operation and locking

Without some kind of locking mechanism, multithreaded programs cannot support complex requirements. To this end, Atomics API provides a way to mimic Linux Futex (Fast user Space Mutex, fast user-space mutex). Although these methods themselves are very simple, they can be used as basic components of a more complex locking mechanism.

All atomic Futex operations can only be used in the Int32Array view and can only be used within the worker thread.

III. Cross-context messages

Cross-document messages, sometimes called XDM (cross-document messaging), are the ability to pass information between different execution contexts, such as different worker threads or pages from different sources.

IV. Encoding API

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

5. File API and Blob API1, File types

File API is still based on the file input fields in the form, but adds the ability to access file information directly. HTML5 adds a files collection to the file input elements on DOM. When the user selects one or more files in the file field, the files collection contains a set of File objects that represent the selected files, each File object has some read-only properties.

2. FileReader type

The FileReader type represents an asynchronous file reading mechanism, and FileReader can be thought of as similar to XMLHttpRequest, except that it is used to read files from the file system rather than from the server. The FileReader type provides several ways to read file data.

ReadAsText (file,encoding); / / read plain text 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 the file and save the binary data for each character in the result attribute

ReadAsArrayBuffer (file); / / read the file and save the contents of the file as ArrayBuffer in the result attribute

3. FileReaderSync type

A synchronized version of the FileReader type.

4. Blob and partial read

In some cases, you may need to read part of the file instead of the whole file, so the File object provides a method called slice (). The slice () method takes two parameters: the start byte and the number of bytes in the Yaodu area. This method returns an instance of Blob, and Blob is actually a superclass of File.

Blob stands for binary large objects and is the type of encapsulation of unmodifiable binary data by JavaScript. Arrays containing strings, ArrayBuffers, ArrayBufferViews, and even other Blob can be used to create blob. The Blob constructor can take an options parameter and specify the MIME type in it.

VI. Streams API1, application scenarios

Streams API is created to solve a simple but fundamental problem: how do Web applications consume ordered small chunks of information instead of large chunks of information? There are two main application scenarios for this capability.

Large chunks of data may not be available all at once. The response to a network request is a typical example. The network load is delivered in the form of continuous packets, while streaming allows applications to be used as soon as the data arrives, without having to wait until all the data is loaded.

Large chunks of data may need to be processed in small parts. Video processing, data compression, image coding, and JSON parsing are all examples that can be processed in small parts without having to wait for all the data to be processed in memory.

2. Understanding flow

Streams API defines three streams:

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

Writable stream: a stream that can be written to a block through a public interface. The producer (consumer) writes data to the stream, and the data is internally passed into the underlying data slot (sink).

Conversion stream: consists of two streams, writable streams for receiving data and readable streams for outputting data. These two stream quality checks are conversion programs (transformer) that can check and modify the stream content as needed.

7. Web Cryptography API

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

Many people use Math.random () when they need to generate random numbers. This method is implemented in the browser as a pseudo-random number generator (PRNG,PseudoRandom Number Generator). The so-called pseudo means that the process of generating values is not really random. The values generated by PRNG only simulate random properties. The browser's PRNG does not use a real random source, but 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 to a new random number. For example, the V8 engine uses an algorithm called xorshift128+ to perform this modification.

Because the algorithm itself is fixed and its input is only the previous state, the order of random numbers is also determined. Xorshift128+ uses a 128bit internal state, and the algorithm is designed so that any initial state produces 2128-1 pseudo-random values before repeating itself. This kind of cycle is called a permutation cycle, and the length of this cycle is called a cycle. Obviously, if an attacker knows the internal state of PRNG, he can predict the pseudo-random values generated later. If a developer inadvertently uses PRNG to generate a private key for encryption, an attacker can take advantage of 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. In order to solve this problem, cryptographic secure pseudorandom number generator (CSPRNG,Cryptographically Secure PseudoRandom Number Generator) adds an additional entropy as input, such as testing hardware time or other unpredictable behavior of the system characteristics, although the speed is not as fast as PRNG, but the resulting value is more difficult to predict, can be used for encryption.

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 () writes random values to its typed array as an argument. The class of the stereotyped array is not important because the underlying buffer is populated with random binary bits.

These are all the contents of the article "what are File API, Streams API and Web Cryptography API in JavaScript?" Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

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