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:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAATUAAAGhCAIAAACPirQGAAAPUWlDQ1BJQ0MgUHJvZmlsZQAAeAGtWHk4lF3/P7MbYxkaa2hCdrIv2ZfIvu9kHYxljLFkya6kRSgKUSHJUioqsiRSChVlaSFLkaQQJdt7D0/Pc72/3/Ve7z/vmWvO+ZzP+W73+c7c3/vcALDxeVGpwXAAQAglgmZjpEd0cnYhYt4AGPRhAfxAxssnnKprZWUGifyHtjwAyUKtX5pui3HG029Mr7qcUClmEZjTTvkPSn9oFhrkEACYFEQQ/Leto 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);