Method description:
Write data to the file asynchronously. If the file already exists, the original content will be replaced.
Grammar:
fs.writeFile(filename, data, [options], [callback(err)])
Since this method belongs to the fs module, the fs module needs to be introduced before use (var fs= require(“fs”) )
Receive parameters:
filename (String) File name
data (String | Buffer) The content to be written can be string or buffer data.
options (Object) option array object, including:
· encoding (string) Optional value, default 'utf8', when data is buffer, the value should be ignored.
· mode (Number) File read and write permissions, default value 438
·flag (String) Default value ‘w’
callback {Function} callback, passing an exception parameter err.
Example:
fs.writeFile('message.txt', 'Hello Node', function (err) {
if (err) throw err;
console.log('It's saved!');
});
Source code:
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);
}
});
};