O'Reilly logo

Node for Front-End Developers by Garann Means

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Storing Data in Files

Though you probably wouldn’t choose to store data in a text file over a database, there might be times when you want to write to and read from something highly portable—for example, if you were managing values in a config file. Writing to a file can’t give us the control over individual properties a data store can, of course, and it’s very slow, but there are still applications where a text file makes sense. Like writing to a database, writing to a file is done asynchronously, so if we want verification that it was done we’ll need to take any dependent actions from within a callback:

var connect = require("connect"),
  fs = require("fs");
      
connect(
  connect.static(__dirname + "/public"),
  connect.bodyParser(),
  function(req, res) {
    var firstName = req.body.firstName,
      lastName = req.body.lastName,
      userName = firstName + " " + lastName,
      stream;
    
    if (firstName || lastName) {
      // create a stream, and create the file if it doesn't exist
      stream = fs.createWriteStream("user_name.txt");
    } else {
      return;
    }
      
    stream.on("open", function() {
      // write to and close the stream at the same time
      stream.end((firstName + "," + lastName + "\n"), "utf-8");    
      var html = "<!doctype html>" +
        "<html><head><title>Hello " + userName + "</title></head>" +
        "<body><h1>Hello, " + userName + "!</h1></body></html>";
        
      res.end(html);
    });
  }
).listen(8000);

Setting the data is easy, but it’s also fragile. We have to check that we’ve actually received data to avoid overwriting good data with bad, and if we had ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required