Instructions for the fs.writeFile method in node.js
- 2020-05-05 10:51:51
- OfStack
method description:
Write data to a file asynchronously, and if the file already exists, the original content will be replaced.
syntax:
fs.writeFile(filename, data, [options], [callback(err)])
Since this method belongs to the fs module, it is necessary to introduce the fs module (var fs= require(" fs "))
before using itreceive parameters:
filename (String)
data (String | Buffer) is going to write something that can make a string or buffer data.
options (Object
· encoding (string) optional value, default 'utf8', when data buffer, the value should be ignored.
· mode (Number) file read and write permissions, default value of 438
flag The default value of is' 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:
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);
}
});
};