The simplest method for writing data to a file is to use one of the writeFile()
methods. These methods write the full contents of a string or buffer to a file. The following is the syntax for writeFile()
methods:
fs.writeFile(path, data, [options], callback)
fs.writeFileSync(path, data, [options])
The path
parameter specifies the path to the file, which can be relative or absolute. The data
parameter specifies the String
or Buffer
object that will be written to the file. The optional options
parameter is an object that can contain encoding
, mode
, and flag
properties that define the string encoding as well as the mode and flags used when opening the file. The asynchronous method also requires the callback
parameter, which will be called when the file write has been completed.
The code in Listing 6.1 shows how to implement a simple asynchronous fileWrite()
request to store a JSON string of a config
object in a file. Figure 6.1 shows the output of the code in Listing 6.1.
01 var fs = require('fs'),
02 var config = {
03 maxFiles: 20,
04 maxConnections: 15,
05 rootPath: "/webroot"
06 };
07 var configTxt = JSON.stringify(config);
08 var options = {encoding:'utf8', flag:'w'};
09 fs.writeFile('../data/config.txt', configTxt, options, function(err){
10 if (err){
11 console.log("Config Write Failed.");
12 } else {
13 console.log("Config Saved.");
14 }
15 });