This article mainly introduces node. fs. description of the writeFileSync method. This article introduces fs. writeFileSync method description, syntax, receiving parameters, use instances, and implementation source code. For more information, see
Method description:
Synchronous version of fs. writeFile ().
Syntax:
The Code is as follows:
Fs. writeFileSync (filename, data, [options])
Because this method belongs to the fs module, we need to introduce the fs module (var fs = require ("fs") before use "))
Receiving parameters:
Filename (String) file name
Data (String | Buffer) the content to be written, which can be String or buffer data.
Options (Object) option array Object, including:
· Optional value of encoding (string). The default value is 'utf8'. When data enables buffer, this value should be ignored.
· Mode (Number) file read and write permissions. The default value is 438.
· Flag (String) Default Value: 'W'
Example:
The Code is as follows:
Fs.writeFileSync('message.txt ', 'Hello node ');
Source code:
The Code 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 );
}
};