How to use the appendFile function from fs

Find comprehensive JavaScript fs.appendFile code examples handpicked from public code repositorys.

fs.appendFile is a Node.js function that appends data to a file, creating the file if it does not already exist.

8
9
10
11
12
13
14
15
16
17
nodejs中有一个非常重要的模块叫做fs。这个模块提供了许多非常实用的函数来访问文件系统并与文件系统进行交互。

简单统计一下,fs提供了下面这么多种使用的文件操作方法:

* fs.access(): 检查文件是否存在,以及 Node.js 是否有权限访问。
* fs.appendFile(): 追加数据到文件。如果文件不存在,则创建文件。
* fs.chmod(): 更改文件(通过传入的文件名指定)的权限。相关方法:fs.lchmod()、fs.fchmod()。
* fs.chown(): 更改文件(通过传入的文件名指定)的所有者和群组。相关方法:fs.fchown()、fs.lchown()。
* fs.close(): 关闭文件描述符。
* fs.copyFile(): 拷贝文件。
fork icon192
star icon570
watch icon16

+ 5 other calls in file

97
98
99
100
101
102
103
104
105
106
var result = await fetch(`https://sonar.omnisint.io/subdomains/${args[1]}`);
var json = await result.json();
json.splice(0, json.length, ...(new Set(json)));
logprint('?', senderid, `Scan subdomains from ${args[1]}`)
for (var i=0; i<json.length; i++) {
    fs.appendFile(`temp/${senderid}-subdo-${args[1]}.txt`, `${json[i]}\n`, err => {
        if (err) throw err;
    })
}
fs.readFile(`temp/${senderid}-subdo-${args[1]}.txt`, 'utf8', function(err, data) {
fork icon1
star icon3
watch icon0

+ 4 other calls in file

How does fs.appendFile work?

fs.appendFile() is a method in Node.js that appends data to a file asynchronously, creating the file if it does not exist. It takes the file path, data to be appended and an optional options object as arguments, and writes the data to the end of the file. If the file already exists, the data is appended to the existing contents of the file.

986
987
988
989
990
991
992
993
994
995
996
997
  }
  msg_formatted += ' ' + msg + '\n';


  process.stdout.write(msg_formatted);


  fs.appendFile(process.cwd() + "/env_data/babot.log", msg_formatted,
    function (err) {
    if (err) throw err;
  });
}
fork icon0
star icon1
watch icon1

39
40
41
42
43
44
45
46
47
48
{
	this.#_last_presence = newUser;

	if(!fsc.existsSync(__dirname + '/discord_logging/status/' + newUser.userId))
	{
		await fs.appendFile(__dirname + '/discord_logging/status/' + newUser.userId, "", {encoding: 'utf-8'});
	}
	/*if(!fsc.existsSync(__dirname + '/discord_logging/online/' + newUser.userId))
	{
		await fs.appendFile(__dirname + '/discord_logging/online/' + newUser.userId, "", {encoding: 'utf-8'});
fork icon0
star icon1
watch icon1

+ 3 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
const fs = require("fs");

const filePath = "./example.txt";
const data = "This is some data to append to the file.";

fs.appendFile(filePath, data, function (err) {
  if (err) throw err;
  console.log("Data appended to file successfully!");
});

In this example, the fs.appendFile method is used to append the data string to the example.txt file. The filePath variable contains the path to the file. The callback function is executed when the operation is complete, and it logs a message to the console indicating that the data was successfully appended to the file. If an error occurs during the operation, the error is thrown.

45
46
47
48
49
50
51
52
53
54
appendPingRecordToCSV(pingrecord) {
  let {destIP, start, duration, packetSize, wasSuccess} = pingrecord;
  start = start.replace(',', '');
  const rowString = [destIP, start, duration, packetSize, wasSuccess].join(',') + '\n';
  const outputFilePath = path.join(CONSTANTS.OUTPUT_DIR_PATH, CONSTANTS.PING_RESULTS_FILE_NAME);
  fs.appendFile(outputFilePath, rowString, function (err) {
    if (err) {
      appStateLogger.error(err);
    }
  });
fork icon0
star icon0
watch icon1

968
969
970
971
972
973
974
975
976
977
const pre = `${date.toISOString()} | ${processTag} ${tag} : `;
const finalMessage = message.replace(/\n(.*)/g, `\n${pre}$1`);
const noOpCallback = () => {};

if (!logFileSync) {
  fs.appendFile(logFilePath, `${pre + finalMessage}\n`, {
    encoding: 'utf-8',
    flag: 'a',
  }, noOpCallback);
}
fork icon0
star icon0
watch icon1

1566
1567
1568
1569
1570
1571
1572
1573
1574
const { servicePath: serviceDir } = await fixtures.setup('aws');
const localPluginDir = path.join(serviceDir, 'node_modules', 'local-plugin');
const parentPluginDir = path.join(serviceDir, '..', 'node_modules', 'parent-plugin');
installPlugin(localPluginDir, SynchronousPluginMock);
installPlugin(parentPluginDir, PromisePluginMock);
await fsp.appendFile(
  path.join(serviceDir, 'serverless.yml'),
  'plugins:\n  - local-plugin\n  - parent-plugin'
);
fork icon0
star icon0
watch icon961

57
58
59
60
61
62
63
64
65
66
var writtenOne = false;
var writeChain = function(callback){
    var item = next();
    if(item){
        var writable = (writtenOne?",\n":"\n")+JSON.stringify(item)
        fs.appendFile(url, writable, function(err){
            if(!writtenOne) writtenOne = true;
            writeChain(callback);
        });
    }else{
fork icon0
star icon0
watch icon2

+ 3 other calls in file

106
107
108
109
110
111
112
113
114
115
  database.push(data)
  // convert the object to a string
  const stringToAppend = JSON.stringify(database) + '\n';

  // open the file for appending
  fs.appendFile(filePath, stringToAppend, function (err) {
    if (err) throw err;
  });
}
else image_count -- //this is because img in line 75 incremented the count
fork icon0
star icon0
watch icon1

16
17
18
19
20
21
22
23
24
25
if(err) {
   const now = new Date();
   now.setUTCHours(now.getUTCHours() + 5);
   now.setUTCMinutes(now.getUTCMinutes() + 30);
   const istTime = now.toISOString().slice(0, 19).replace('T', ' ');
   fs.appendFile('ErrorLogs/errorLogs.txt', istTime+"\n", (err)=>{});
   fs.appendFile('ErrorLogs/errorLogs.txt', err.toString()+"\n\n", (err)=>{});
   res.status(500).send({error : "Query Error... Contact DB Admin"});

}
fork icon0
star icon0
watch icon1

+ 13 other calls in file

108
109
110
111
112
113
114
115
116
117
  await finished(Readable.fromWeb(body).pipe(stream));
}

async handleBanList(gamertag) {
  await this.downloadFile(`/games/${this.config.Nitrado.UserID}/noftp/dayzxb/ban.txt`, './logs/ban.txt').then(() => {
    fs.appendFile('./logs/ban.txt', gamertag, (err) => {
      if (err) throw err;
    });    
  });
}
fork icon0
star icon0
watch icon2

38
39
40
41
42
43
44
45
46
47
48
49
}


{
  const fileName = path.resolve(tmpdir.path, 'appendFile');
  fs.appendFileSync(fileName, 'ABCD', options);
  fs.appendFile(fileName, 'ABCD', options, common.mustCall(errHandler));
}


if (!common.isIBMi) { // IBMi does not support fs.watch()
  const watch = fs.watch(__filename, options, common.mustNotCall());
fork icon0
star icon0
watch icon0

39
40
41
42
43
44
45
46
47
48
49
50
assert.throws(() => {
  fs.writeFileSync('path', 'data', options);
}, expectedError);


assert.throws(() => {
  fs.appendFile('path', 'data', options, common.mustNotCall());
}, expectedError);


assert.throws(() => {
  fs.appendFileSync('path', 'data', options);
fork icon0
star icon0
watch icon0