Home >Web Front-end >JS Tutorial >Instructions for using the fs.writeSync method in node.js_node.js

Instructions for using the fs.writeSync method in node.js_node.js

WBOY
WBOYOriginal
2016-05-16 16:27:061663browse

Method description:

Synchronized version of fs.write() . Write to file (based on file descriptor).

Grammar:

Copy code The code is as follows:

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:

Copy code 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:

Copy 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);
};
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn