Method description:
Synchronized version of fs.write() . Write to file (based on file descriptor).
Grammar:
fs.writeSync(fd, buffer, offset, length[, position])
fs.writeSync(fd, data[, position[, encoding]])
Since this method belongs to the fs module, the fs module needs to be introduced before use (var fs= require(“fs”) )
Receive parameters:
fd File descriptor.
buffer The buffer into which data will be written. It is best to set the buffer size to a multiple of 8, which is more efficient.
offset The offset written to the buffer
length (integer) Specifies the length of the file read in bytes
position (integer) Specifies the starting position of file reading. If this item is null, data will be read starting from the position of the current file pointer.
encoding (String) Character encoding
Example:
//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:
// 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);
};