Method description:
Synchronous version of fs.write(). Write to the file (according to the file descriptor).
grammar:
The code copy is as follows:
fs.writeSync(fd, buffer, offset, length[, position])
fs.writeSync(fd, data[, position[, encoding]])
Since this method belongs to the FS module, it is necessary to introduce the FS module before use (var fs= require("fs") )
Receive parameters:
fd file descriptor.
buffer, data will be written. The buffer size setting is preferably multiple of 8, which is more efficient.
offset write to offset buffer
length (integer) Specifies the length of the file reading bytes
position (integer) Specifies the starting position for file reading. If this item is null, data will be read from the position of the current file pointer.
encoding ( String ) character encoding
example:
The code copy 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 copy 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);
};