Description of the fs. writeFile method in node. js, node. jsfs
Method description:
Write data to a file asynchronously. If the file already exists, the original content will be replaced.
Syntax:
Copy codeThe 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:
Copy codeThe Code is as follows:
Fs.writeFile('message.txt ', 'Hello node', function (err ){
If (err) throw err;
Console. log ('It \'s saved! ');
});
Source code:
Copy codeThe 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 );
}
});
};