This article mainly introduces node. fs. description of writeSync method. This article introduces fs. writeSync method description, syntax, receiving parameters, use instances and implementation source code. For more information, see
Method description:
Synchronous version of fs. write (). Write a file (based on the file descriptor ).
Syntax:
The Code is as follows:
Fs. writeSync (fd, buffer, offset, length [, position])
Fs. writeSync (fd, data [, position [, encoding])
Because this method belongs to the fs module, we need to introduce the fs module (var fs = require ("fs") before use "))
Receiving parameters:
Fd file descriptor.
Buffer, data will be written. The buffer size is preferably a multiple of 8, which is more efficient.
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.
Encoding (String) character encoding
Example:
The Code is as follows:
// Fs. writeSync (fd, buffer, offset, length [, position])
Var fs = require ('fs ');
Fs.open('content.txt ', 'A', function (err, fd ){
If (err ){
Throw err;
}
Var data = '123123123 hello world ';
Var buf = new Buffer (8 );
Fs. writeSync (fd, buf, 0, 8, 0 );
Fs. close (fd, function (err ){
If (err ){
Throw err;
}
Console. log ('file closed ');
})
})
// Fs. writeSync (fd, data [, position [, encoding])
Var fs = require ('fs ');
Fs.open('content.txt ', 'A', function (err, fd ){
If (err ){
Throw err;
}
Var data = '123123123 hello world ';
Fs. writeSync (fd, data, 0, 'utf-8 ');
Fs. close (fd, function (err ){
If (err ){
Throw err;
}
Console. log ('file closed ');
})
})
Source code:
The Code is as follows:
// Usage:
// Fs. writeSync (fd, buffer, offset, length [, position]);
// OR
// Fs. writeSync (fd, string [, position [, encoding]);
Fs. writeSync = function (fd, buffer, offset, length, position ){
If (util. isBuffer (buffer )){
If (util. isUndefined (position ))
Position = null;
Return binding. writeBuffer (fd, buffer, offset, length, position );
}
If (! Util. isString (buffer ))
Buffer + = '';
If (util. isUndefined (offset ))
Offset = null;
Return binding. writeString (fd, buffer, offset, length, position );
};