Node. js entry-10.api: Io

Source: Internet
Author: User
Tags readfile stream api

I/O is a very important part that distinguishes node from other frameworks. This chapter will explain how it achieves node non-blocking I/O.

  Streams

Stream API is an abstract interface that helps many parts of node perform uninterrupted input and output operations. Stream API provides some common methods and attributes for its implementation classes. streams can be readable, writable, or both, and both implement eventemitter and emit events.

Readable streams

Readable streams provides a series of methods and events that allow us to access data from the data source. Basically, a readable stream is used to trigger data events. It also provides some attributes that allow you to configure the size and speed of the obtained data. Let's take a look at the following example. When we read a file from a file, each time data is readable, a data event is triggered.

var fs = require('fs');var filehandle = fs.readFile('data.txt', function(err, data) {  console.log(data)});

Usually we need to store the data in a variable and output the results together when stream ends.

var spool = "";stream.on('data', function(data) {  spool += data;});stream.on('end', function() {  console.log(spool);});

  

  (File System) filesystem

When we need to access files on the hard disk, we need to use the filesystem module. It is very close to POSIX-style file I/O and provides asynchronous and synchronous versions for all methods. We recommend that you use an Asynchronous Method. Although this will slightly complicate the code, it allows you to access multiple files in parallel and reduce the script running time.

When we use an asynchronous method, we often encounter the issue of code execution sequence. The asynchronous mode does not guarantee the execution sequence. When an operation depends on another operation, the following error occurs:

var fs = require('fs');fs.readFile('warandpeace.txt', function(e, data) {  console.log('War and Peace: ' + data);});fs.unlink('warandpeace.txt');

The problem here is that when we haven't finished reading the file content, we may have deleted the file. To solve this problem, we need to slightly modify the code and use internal callback, as shown below:

var fs = require('fs');fs.readFile('warandpeace.txt', function(e, data) {  console.log('War and Peace: ' + data);  fs.unlink('warandpeace.txt');});

 

Buffers

Although node uses JavaScript as the development language, it is different from the traditional execution environment of JavaScript. For example, Javascript in the browser mostly executes functions, while processing the binary data is relatively small. Although JavaScript supports bitwise operations, it does not represent native binary data. Node provides the buffer class for you to operate binary data.

 

It is very important to note that when you copy a string to the buffer, they will be stored in a binary format. Of course, you can also convert the buffer into a string. Three parameters can be used to create a buffer object. The first parameter is the buffer length, the second parameter is the bytes array, and the third parameter is the string. For example, input the following statement in node repl and set the buffer length to 10:

new Buffer(10);

Node will provide a memory area with a length of 10 for the buffer, but this area is just released by the system, and the content in it has not been cleared yet, therefore, the running results of the preceding statements are different each time.

In node, the UTF-8 encoding format is used by default. Of course, you can change the encoding format.

new Buffer('foobarbaz');new Buffer('foobarbaz', 'ascii');new Buffer('foobarbaz', 'utf8');new Buffer('é');new Buffer('é', 'utf8');new Buffer('é', 'ascii');

Node provides other methods to operate the buffer, such as buffer. Write (). Input the string and index (0 by default) parameters. If the buffer has enough space, we will replace the buffer content with the string content starting from the specified index; otherwise, we will intercept the string to adapt to the length of the buffer from the start position of the index to the end. Finally, the length of the modified buffer content is returned.

var b = new Buffer(1);bb.write('a');bb.write('é');b

Define a buffer with a length of 1 and overwrite the buffer content 'A' from index 0. Then, the buffer content is modified and the index is increased to 1. The buffer content is overwritten again. At this time, there is no space in the buffer from Index 1, so the overwriting fails and the buffer content does not change. The execution result is as follows.

Let's look at another example:

var b = new Buffer(5);b.write('fffff');bb.write('ab', 1);b

Create a buffer with a length of 5. the overwriting content is 'ffffff', And the overwriting content is 'AB' from Index 1. Let's look at the running result.

  

The content of this lesson is over. If you have any questions, please leave me a message.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.