This article mainly introduces node. fs. description of the writeFile method. This article introduces fs. writeFile method description, syntax, receiving parameters, use instances and implementation source code. For more information, see
Method description:
Write data to a file asynchronously. If the file already exists, the original content will be replaced.
Syntax:
The Code is as follows:
Fs. writeFile (filename, data, [options], [callback (err)])
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'
Callback {Function} callback, passing an exception parameter err.
Example:
The Code is as follows:
Fs.writeFile('message.txt ', 'Hello node', function (err ){
If (err) throw err;
Console. log ('It \'s saved! ');
});
Source code:
The Code is as follows:
Fs. writeFile = function (path, data, options, callback ){
Var callback = maybeCallback (arguments [arguments. length-1]);
If (util. isFunction (options) |! 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 ';
Fs. open (path, options. flag | 'w', options. mode, function (openErr, fd ){
If (openErr ){
If (callback) callback (openErr );
} Else {
Var buffer = util. isBuffer (data )? Data: new Buffer (''+ data,
Options. encoding | 'utf8 ');
Var position =/a/. test (flag )? Null: 0;
WriteAll (fd, buffer, 0, buffer. length, position, callback );
}
});
};