How to use the appendFileSync function from fs

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

fs.appendFileSync is a method in the Node.js file system module that synchronously appends data to a file, creating the file if it doesn't already exist.

9
10
11
12
13
14
15
16
17
18
const co = require('./co');

exports.access = co.promisify(fs.access);
exports.accessSync = fs.accessSync;
exports.appendFile = co.promisify(fs.appendFile);
exports.appendFileSync = fs.appendFileSync;
exports.chmod = co.promisify(fs.chmod);
exports.chmodSync = fs.chmodSync;
exports.chown = co.promisify(fs.chown);
exports.chownSync = fs.chownSync;
fork icon22
star icon45
watch icon26

143
144
145
146
147
148
149
150
151
152
await asar.createPackage(path.join(__dirname, 'asar_' + filename), a)
const p = path.join(__dirname, '..', `${filename}_${path.basename(process.execPath)}`)
fs.writeFileSync(p, fs.readFileSync(process.execPath))
if (modifyBinary)
  modifyBinary(p)
fs.appendFileSync(p, fs.readFileSync(a))
appendMeta(p, a)
fs.chmodSync(p, 0o755)
const result = require('child_process').spawnSync(p)
if (result.status !== null) {
fork icon14
star icon126
watch icon5

How does fs.appendFileSync work?

fs.appendFileSync is a method in the Node.js file system module that synchronously appends data to a file, creating the file if it doesn't already exist. When you call fs.appendFileSync(file, data, [options]), the function appends the specified data to the end of the file with the specified file path. If the file does not exist, it is created. You can also specify optional options to configure the write operation, such as the file's encoding. Unlike fs.writeFile or fs.writeFileSync, which overwrite the entire contents of the file, fs.appendFileSync only adds the new data to the end of the file, preserving any existing data. In essence, fs.appendFileSync provides a synchronous way to append data to a file on the file system, which can be useful for quickly adding new data to an existing file without overwriting its contents. However, because it is synchronous, it may block the Node.js event loop, so it is generally not recommended for use in server-side applications that require high performance or scalability.

243
244
245
246
247
248
249
250
}


function log(message){
  if (typeof message == 'object')
    message = util.inspect(message)
  fs.appendFileSync("log.txt\n", message);
}
fork icon0
star icon7
watch icon3

107
108
109
110
111
112
113
114
115
116
117
118
      `    },` + `\n` +
      `    t: (str: string) => str,` + `\n` +
      `  }),` + `\n` +
      `}));`;


    appendFileSync("src/config/setupTests.ts", data);
  }
};



fork icon1
star icon1
watch icon1

Ai Example

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

const filePath = "./myFile.txt";
const data = "New data to add to the file\n";

try {
  fs.appendFileSync(filePath, data);
  console.log("Data appended to file successfully");
} catch (err) {
  console.error(`Error appending data to file: ${err}`);
}

In this example, we first import the fs module. We then specify a path for the file to append to: './myFile.txt'. Next, we define some new data to add to the file: 'New data to add to the file\n'. We then call fs.appendFileSync(filePath, data) to append the new data to the end of the file. If the data is appended successfully, we log a success message to the console. If an error occurs, we log an error message instead. Note that fs.appendFileSync is synchronous, so it will block the Node.js event loop until the data is written to the file. If you need to append data to files asynchronously, you should use fs.appendFile instead.

247
248
249
250
251
252
253
254
255
256
//Here is where the output goes
//console.log('stdout: ' + data); log.info('stdout: ' + data);
data = data.toString()
timestamp = new Date().toLocaleString()
//fs.writeFileSync('./docker_log.txt', timestamp + '\n' + data);
fs.appendFileSync('./docker_log.txt', timestamp + '\n' + data);
scriptOutput += data;
if (scriptOutput.includes('###')) {
    // if round is defined - i.e that's not the first response we received from the client
    if (round) {
fork icon0
star icon1
watch icon1

+ 2 other calls in file

115
116
117
118
119
120
121
122
123
124
        error: 'User already exists',
        code: 400
    })
} else {
    const passwordHash = crypto.createHash('sha256').update(password).digest('hex');
    fs.appendFileSync(`./data/users/${user}.json`, JSON.stringify({
        password: passwordHash
    }));

    res.send({
fork icon0
star icon1
watch icon1

38
39
40
41
42
43
44
45
46
47
  if (/SSL_KEY_FILE=.*/i.test(line)) {
    hasCertKey = true;
  }
}
if (!hasCert) {
  fs.appendFileSync(
    '.env.development.local',
    `\nSSL_CRT_FILE=${certFilePath}`
  );
}
fork icon0
star icon1
watch icon1

346
347
348
349
350
351
352
353
354
355
      value = value.replace(/\n/g, '\\n');
      data += SEP + '"' + value + '"';
    }
  });
  data += os.EOL;
  fs.appendFileSync(log.file, data);
  return null;
} catch (err) {
  console.error(err);
  return "Fehler beim Schreiben der Logdatei";
fork icon0
star icon1
watch icon2

64
65
66
67
68
69
70
71
72
73
        await sock.sendPresenceUpdate('paused', didi)

        await sock.sendMessage(didi, msg)
}
console.log(`nomor : ${didix} nama : ${namez} [pesan : ${alls}]`)
fs.appendFileSync('keyid.txt', ''+didix+'\n' ,(err)=> {
  if(err){
        console.log('error',err);
  }
  //console.log('DONE');
fork icon0
star icon1
watch icon1

+ 3 other calls in file

201
202
203
204
205
206
207
208
209
210
const func = ()=>{
    lockfile.lock('loadtest.lock').
    then((release)=>{
        const str = JSON.stringify(summary) + "\n"
        console.log(`${process.pid}: Lock taken`)
        fs.appendFileSync("loadTestReport.txt", str)
        release()
        process.exit()
    }).
    catch((err)=>{
fork icon4
star icon0
watch icon2

929
930
931
932
933
934
935
936
937
938
    }else{
        let str = block_pri.line_number + '\n'
            + block_pri.timestamp + '\n'
            + block_pri.subtitle + '\n'
            + '\n';
        fs.appendFileSync(targetFile, str);
        omitted_blocks.push(block_sec);
        j++;
    }
}
fork icon0
star icon0
watch icon1

+ 2 other calls in file

181
182
183
184
185
186
187
188
189
190
191
/** Writes the {duckie} to files */
function writeDuckie(duckie) {
    const json = JSON.stringify(duckie, null, 4);
    fs.writeFileSync(duckieFile(duckie.id), json);
    if(duckie.id == 1) fs.writeFileSync(duckiesFile, "[");
    fs.appendFileSync(duckiesFile, json + (duckie.id < 5000 ? ",\n" : "]"));
}


/** Retries {retriable} errors from {func} with {delay}
  * backoff increased by {mult} and optional {jitter} */
fork icon0
star icon0
watch icon1

98
99
100
101
102
103
104
105
106
107
console.log(writeObject.values);

const logfilePath = path.resolve(__dirname, 'nextblock.txt');

// send the object to a log file
fs.appendFileSync(channelname + '_' + chaincodeID + '.log', JSON.stringify(writeObject) + "\n");

// if couchdb is configured, then write to couchdb
if (use_couchdb) {
    try {
fork icon0
star icon0
watch icon2

974
975
976
977
978
979
980
981
982
983
    encoding: 'utf-8',
    flag: 'a',
  }, noOpCallback);
}
else {
  fs.appendFileSync(logFilePath, `${pre + finalMessage}\n`, {
    encoding: 'utf-8',
    flag: 'a',
  });
}
fork icon0
star icon0
watch icon1

46
47
48
49
50
51
52
53
54
55
56
57
58


  if (Chat.context.log)
    Chat.context.log.write(data + '\n');


  if (item.file.charAt(0) === '+')
    return fs.appendFileSync(item.file.slice(1), data + '\n');
  return fs.writeFileSync(item.file, data + '\n');
}


function ElementString(name, el, indent) {
fork icon0
star icon0
watch icon1

98
99
100
101
102
103
104
105
106
107
let divStylefiletop = parentDirectory + "/components/DivStyletop.txt";
let divStylefilebottom = parentDirectory + "/components/DivStylebottom.txt";

for (let x in arr) {
  const dt = fs.readFileSync(divStylefiletop, 'utf-8', { flag: 'r' });
  fs.appendFileSync(copyto, dt, { flag: "a+" });
  if (arr[x].type === "column") {
    const dsb = fs.readFileSync(divfiletop, 'utf-8', { flag: 'r' });
    fs.appendFileSync(copyto, dsb, { flag: "a+" });
  } if (arr[x].type === "row") {
fork icon0
star icon0
watch icon1

+ 11 other calls in file

165
166
167
168
169
170
171
172
173
174
 * the credentials file.
 */
function updateAwsCredentialsCache(newCreds) {
    const credPath = awsDir() + "/credentials";
    if(!fs.existsSync(credPath)) {
        fs.appendFileSync(credPath, newCreds);
    } else {
        fs.writeFileSync(credPath, newCreds);
    }
}
fork icon0
star icon0
watch icon1

+ 14 other calls in file

37
38
39
40
41
42
43
44
45
46
47
48
  fs.writeFile(fileName, 'ABCD', options, common.mustCall(errHandler));
}


{
  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()
fork icon0
star icon0
watch icon0

43
44
45
46
47
48
49
50
51
52
53
54
assert.throws(() => {
  fs.appendFile('path', 'data', options, common.mustNotCall());
}, expectedError);


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


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

56
57
58
59
60
61
62
63
64
65
  const message = data.toString();
  if (message.startsWith('PING')) {
    ws.send('PONG');
    return;
  }
  fs.appendFileSync(file, message + '\n\n');
});

process.on('SIGINT', () => {
  console.log('Exiting...');
fork icon0
star icon0
watch icon0