index.js
 1  'use strict'
 2  
 3  module.exports = function parseBytea (input) {
 4    if (/^\\x/.test(input)) {
 5      // new 'hex' style response (pg >9.0)
 6      return new Buffer(input.substr(2), 'hex')
 7    }
 8    var output = ''
 9    var i = 0
10    while (i < input.length) {
11      if (input[i] !== '\\') {
12        output += input[i]
13        ++i
14      } else {
15        if (/[0-7]{3}/.test(input.substr(i + 1, 3))) {
16          output += String.fromCharCode(parseInt(input.substr(i + 1, 3), 8))
17          i += 4
18        } else {
19          var backslashes = 1
20          while (i + backslashes < input.length && input[i + backslashes] === '\\') {
21            backslashes++
22          }
23          for (var k = 0; k < Math.floor(backslashes / 2); ++k) {
24            output += '\\'
25          }
26          i += Math.floor(backslashes / 2) * 2
27        }
28      }
29    }
30    return new Buffer(output, 'binary')
31  }