Method description:
Synchronous version of fs.writeFile().
grammar:
The code copy is as follows:
fs.writeFileSync(filename, data, [options])
Since this method belongs to the FS module, it is necessary to introduce the FS module before use (var fs= require("fs") )
Receive parameters:
filename (String) file name
data (String | Buffer) The content to be written, which can make strings or buffer data.
options (Object) option array object, containing:
・ encoding (string) Optional value, default 'utf8', when data buffers, this value should be ignored.
・ mode (Number) file read and write permissions, default value 438
・ flag (String) default value 'w'
example:
The code copy is as follows:
fs.writeFileSync('message.txt', 'Hello Node');
Source code:
The code copy is as follows:
fs.writeFileSync = function(path, data, options) {
if (!options) {
options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'w' };
} else if (util.isString(options)) {
options = { encoding: options, mode: 438, flag: 'w' };
} else if (!util.isObject(options)) {
throw new TypeError('Bad arguments');
}
assertEncoding(options.encoding);
var flag = options.flag || 'w';
var fd = fs.openSync(path, flag, options.mode);
if (!util.isBuffer(data)) {
data = new Buffer('' + data, options.encoding || 'utf8');
}
var written = 0;
var length = data.length;
var position = /a/.test(flag) ? null : 0;
try {
while (written < length) {
written += fs.writeSync(fd, data, written, length - written, position);
position += written;
}
} finally {
fs.closeSync(fd);
}
};