Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Hour 8. Persisting Data > Writing Data to a File

Writing Data to a File

If your application needs to store small pieces of information that seldom need to be read or written, using text files is a quick, lightweight option. Node.js has a rich File System module that allows you to interact with the filesystem however you need to. Writing data to a file looks like Listing 8.1.

Listing 8.1. Writing Data to a File


var fs = require('fs'),
    data = "Some data I want to write to a file";
fs.writeFile('file.txt', data, function (err) {
  if (!err) {
    console.log('Wrote data to file.txt');
  } else {
    throw err;
  }
});


The File System module is required on the first line and then a variable is set to hold the data that should be written to the file. The writeFile method is then used to write the data to a file.


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial