Heim  >  Artikel  >  Web-Frontend  >  node.js中的fs.appendFile方法使用说明_node.js

node.js中的fs.appendFile方法使用说明_node.js

WBOY
WBOYOriginal
2016-05-16 16:25:541576Durchsuche

方法说明:

该方法以异步的方式将 data 插入到文件里,如果文件不存在会自动创建。data可以是任意字符串或者缓存。

语法:

复制代码 代码如下:

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

由于该方法属于fs模块,使用前需要引入fs模块(var fs = require(“fs”) )

接收参数:

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}

例子:

复制代码 代码如下:

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

源码:

复制代码 代码如下:

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);
};
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn