3
\$\begingroup\$

I am saving (image) files to PostgreSQL database in my Node.js and Express server application. The code is used to upload user images to server (at the moment it is not restricted to image files in any way though, but that's not the point). The files are sent as multipart requests and they are parsed using Busboy. These are then converted to hex strings which are put to database.

My main concern with this code is the stream handler that reads data from buffer and then concatenates it into a string. Is there a better way to do this and put the file to database?

app.post('/upload', function(req, res, next) {
  //Set busboy to parse file-inputs
  req.busboy.on('file', function(fieldName, file, filename) {
    //File data will be added to this string
    var fileData = '';

    //Add stream handler function for type data.
    //Function concatenates buffered data to fileData string in hex format.
    file.on('data', function(buffer) {
      fileData += buffer.toString('hex');
    });

    //Add stream handler for stream end.
    //Add \x to the beginning of the data to mark that it is hex formatted data.
    //Data string is then put to database.
    file.on('end', function() {
      fileData = '\\x' + fileData;

      //Get database client from pool and make query adding our data to the database.
      pg.connect(process.env.DATABASE_URL, function(err, client, done) {
        if (err) {
          return console.error('error fetching client from pool', err);
        }

        var query = 'INSERT INTO Files(data) VALUES ($1) RETURNING id';
        client.query(query, [fileData], function(err, writeResult) {
          //call `done()` to release the client back to the pool
          done();
          if (err) {
            return console.error('error running query', err);
          }
          client.end();

          var responseObject = {
            status: 'success',
            id: writeResult.rows[0].id,
            url: req.get('host') + '/files/' + writeResult.rows[0].id
          };
          res.json(responseObject);
        });
      });
    });
  });
  req.pipe(req.busboy);
});
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.