Wednesday 17 October 2018

node.js: fs.appendFileSync(path, data[, options]): Append data to a file synchronously

fs.appendFileSync(path, data[, options])
This method appends the data to given file synchronously.

Below table summarizes the arguments associated with appendFileSync function.
Argument
Type
Description
path
string or Buffer or URL or number
Specifies the file name or descriptor.
data
string or Buffer
Data to be written to the file.
options
stirng or Object
Below table summarizes the options provided by appendFileSync method.
Option
Type
Description
encoding
string
Default value is utf8
mode
integer
Default mode is 0o666.
flag
string
Default flag is ‘a’.

'a' - Open file for appending. The file is created if it does not exist.

'ax' - Like 'a' but fails if the path exists.

'a+' - Open file for reading and appending. The file is created if it does not exist.

'ax+' - Like 'a+' but fails if the path exists.

'as' - Open file for appending in synchronous mode. The file is created if it does not exist.

'as+' - Open file for reading and appending in synchronous mode. The file is created if it does not exist.

'r' - Open file for reading. An exception occurs if the file does not exist.

'r+' - Open file for reading and writing. An exception occurs if the file does not exist.

'rs+' - Open file for reading and writing in synchronous mode. Instructs the operating system to bypass the local file system cache.

'w' - Open file for writing. The file is created (if it does not exist) or truncated (if it exists).

'wx' - Like 'w' but fails if the path exists.

'w+' - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).

'wx+' - Like 'w+' but fails if the path exists.

Below table summarizes the modes supported by node.js
Constant (mode)
Octal value
Description
fs.constants.S_IRUSR
0o400
read by owner
fs.constants.S_IWUSR
0o200
write by owner
fs.constants.S_IXUSR
0o100
execute/search by owner
fs.constants.S_IRGRP        
0o40
read by group
fs.constants.S_IWGRP
0o20
write by group
fs.constants.S_IXGRP
0o10
execute/search by group
fs.constants.S_IROTH
0o4
read by others
fs.constants.S_IWOTH
0o2
write by others
fs.constants.S_IXOTH
0o1
execute/search by others
        
Find the below working application.

HelloWorld.js
var fs = require('fs');

var filePath = 'out.txt';

var msg1 = 'Hello, How are you\n';
var msg2 = 'I am fine, How are you?\n';
var msg3 = 'I am fine too, thank you!!!!!\n';

fs.appendFileSync(filePath, msg1);
fs.appendFileSync(filePath, msg2);
fs.appendFileSync(filePath, msg3);

Open 'out.txt', you can see below messages.

Hello, How are you
I am fine, How are you?
I am fine too, thank you!!!!!



Previous                                                 Next                                                 Home

No comments:

Post a Comment