Home  >  Article  >  Web Front-end  >  Instructions for using the fs.appendFile method in node.js_node.js

Instructions for using the fs.appendFile method in node.js_node.js

WBOY
WBOYOriginal
2016-05-16 16:25:541622browse

Method description:

This method inserts data into the file asynchronously. If the file does not exist, it will be created automatically. data can be any string or cache.

Grammar:

Copy code The code is as follows:

fs.appendFile(filename, data, [options], callback)

Since this method belongs to the fs module, the fs module needs to be introduced before use (var fs = require(“fs”) )

Receive parameters:

1. filename {String}

2. data {String | Buffer}

3. options {Object}

encoding {String | Null} default = ‘utf8′

mode {Number} default = 438 (aka 0666 in Octal)

flag {String} default = ‘a’

4. callback {Function}

Example:

Copy code The code is as follows:

var fs = require("fs");
fs.appendFile('message.txt', 'data to append', function (err) {
if (err) throw err;
console.log('The "data to append" was appended to file!');
});

Source code:

Copy code The code is as follows:

fs.appendFile = function(path, data, options, callback_) {
var callback = maybeCallback(arguments[arguments.length - 1]);
if (util.isFunction(options) || !options) {
Options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'a' };
} else if (util.isString(options)) {
options = { encoding: options, mode: 438, flag: 'a' };
} else if (!util.isObject(options)) {
Throw new TypeError('Bad arguments');
}
if (!options.flag)
Options = util._extend({ flag: 'a' }, options);
fs.writeFile(path, data, options, callback);
};
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn