Node.js fs process file Synchronously and Asynchronously

Introduction

The File System module makes a variety of file-handling methods

Synchronously

The .writeFileSync() method will pause execution until a supplied string has been completely written to a designated file.

The .readFileSync() method will pause execution until a designated file has been read completely.

Asynchronously

The .writeFile() method will write a supplied string to a designated file without pausing execution and triggers a callback function when finished.

The .readFile() method supplies the contents of a designated file to a callback function.

The .watchFile() method causes a callback function to be triggered whenever a designated file is altered.

var fs = require("fs"),
  syncFile = "files/runtime_sample_sync.txt",
  asyncFile = "files/runtime_sample_async.txt",
  watchFile = "files/runtime_sample_watch.txt";

fs.writeFileSync(syncFile, "Hello world (synchronously)!");

fs.writeFile(asyncFile, "Hello world (asynchronously)!", function(error) {
  if(error) {/* w  ww  .j  a  va 2  s .  c o m*/
    console.log("Could not write to " + asyncFile + ".");
  } else {
    console.log("Finished writing to " + asyncFile + " asynchronously.");
  }
});
var fileContents = fs.readFileSync(syncFile);
console.log(syncFile + " contents: " + fileContents);

fs.readFile(asyncFile, function(error, data) {
  if(error) {
    console.log("Could not read " + asyncFile + " asynchronously.");
  } else {
    console.log(asyncFile + " contents: " + data);
  }
});
console.log("Watching files...");


console.log("Creating " + watchFile + " synchronously.");
fs.writeFileSync(watchFile, "Hello world (watch me)!");
console.log("Watching " + watchFile + ".");
fs.watchFile(watchFile, function(current, previous) {
  console.log(watchFile + " previous data:");
  console.log(previous);
  console.log(watchFile + " current data:");
  console.log(current);
  console.log(watchFile + " size change: " + (current.size - previous.size) + ".");
});
console.log("Changing " + watchFile + " synchronously.");
fs.writeFileSync(watchFile, "Hello world (watch me, changed)!");
console.log("Finished changing " + watchFile + " synchronously.");



PreviousNext

Related