Writing Files with Node.js

So far, we have been keeping files and other data off of the server and just using the server to store things in memory or sending directly out to clients. There are a plethora of reasons that we might need to capture and save data as it comes through a Socket.

To write a file with Node.js, we use the File System module: fs, in particular the fs.writeFile(filename, data, [options], callback) method:

var fs = require('fs');

fs.writeFile('message.txt', 'Hello Node', function (err) {
  if (err) throw err;
  console.log('It\'s saved!');

To write binary data we need to go a step further. Here is what a Data URL for an image looks like when coming from the browser:
to save it, we need to cut off the "data:image/jpeg;base64," portion, create a "buffer" with the right type and then write it out. The below example works for JPEG images:
// Saving a data URL (server side)
var searchFor = "data:image/jpeg;base64,";
var strippedImage = data.slice(data.indexOf(searchFor) + searchFor.length);
var binaryImage = new Buffer(strippedImage, 'base64');
fs.writeFileSync(__dirname + '/theimage.jpg', binaryImage);