Instructions for the fs.appendFile method in node.js

  • 2020-05-07 19:12:17
  • OfStack

method description:

This method inserts data asynchronously into a file and automatically creates the file if it doesn't exist. data can be any string or cache.

syntax:


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

Since this method belongs to fs module, fs module (var fs = require(" fs ") needs to be introduced before use.)

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:


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:


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);
};


Related articles: