fs.writeFile(file,
data[, options], callback)
This
method writes data to a file asynchronously.
Below
table summarizes the arguments of writeFile function.
Argument
|
Type
|
Description
|
||||||||||||
file
|
string
or Buffer or URL or integer
|
Specifies
the filename or file descriptor.
|
||||||||||||
data
|
string
or Buffer or Unit8Array
|
Data
to be written to the file
|
||||||||||||
options
|
string
or Object
|
Below
table summarizes the options supported by writeFile method.
|
||||||||||||
callback
|
Function
|
Cal
back function take an argument ‘err’. If any error occurs while writing to a
file, then this variable is populated with error information.
|
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 = 'input.txt'; var data = 'I love you the more in that I believe you had liked me for my own sake and for nothing else.'; fs.writeFile(filePath, data, (err) => { if (err) { console.log('Error occured while writing data to a file.'); } else { console.log("Content saved successfully.") } });
Output
Content
saved successfully.
Note
a. The encoding option
is ignored if data is a buffer.
No comments:
Post a Comment