How to Use fs. readSync in node. js _ node. js-js tutorial

Source: Internet
Author: User
This article mainly introduces node. fs. readSync method usage instructions. This article introduces fs. readSync method description, syntax, receive parameters, use instances, and implement Source Code. For more information, see Method description:

Synchronous version of fs. read ().

Method returns a bytesRead (number of bytes read)

Syntax:

The Code is as follows:


Fs. readSync (fd, buffer, offset, length, position)

Because this method belongs to the fs module, we need to introduce the fs module (var fs = require ("fs") before use "))

Receiving parameters:

Fs

Buffer, data will be written.

Offset buffer write offset

Length (integer) specifies the length of the number of bytes that the file reads.

Position (integer) specifies the start position of File Reading. If this parameter is set to null, data is read from the current file pointer.

Example:

The Code is as follows:


Var fs = require ('fs ');
Fs.open('123.txt ', 'R', function (err, fd ){
If (err ){
Console. error (err );
Return;
}
Var buf = new Buffer (8 );
Var readfile = fs. readSync (fd, buf, 0, 8, null );
Console. log (readfile );
})

Source code:

The Code is as follows:


Fs. readSync = function (fd, buffer, offset, length, position ){
Var legacy = false;
If (! Util. isBuffer (buffer )){
// Legacy string interface (fd, length, position, encoding, callback)
Legacy = true;
Var encoding = arguments [3];
AssertEncoding (encoding );
Position = arguments [2];
Length = arguments [1];
Buffer = new Buffer (length );
Offset = 0;
}
Var r = binding. read (fd, buffer, offset, length, position );
If (! Legacy ){
Return r;
}
Var str = (r> 0 )? Buffer. toString (encoding, 0, r ):'';
Return [str, r];
};

Related Article

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.