Method Description:
Writes data to a file asynchronously, and the original content is replaced if the file already exists.
Grammar:
Copy Code code as follows:
Fs.writefile (filename, data, [options], [Callback (ERR)])
Because this method belongs to the FS module, it is necessary to introduce FS module (VAR fs= require ("FS") before use.
Receive parameters:
FileName (String) file name
Data (String | Buffer) will be written to the content that can be used to make string or buffer data.
Options (object) Option array object that contains:
· Encoding (string) optional value, default ' utf8′, which should be ignored when data makes buffer.
· Mode (number) file read and Write permission, default value 438
· Flag (String) Default value ' W '
callback {Function} callback, passing an exception parameter err.
Example:
Copy Code code as follows:
Fs.writefile (' Message.txt ', ' Hello Node ', function (err) {
if (err) throw err;
Console.log (' it\ ' s saved! ');
});
Source:
Copy Code code 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);
}
});
};