Node.JS convierte datos binarios de longitud variable a jpeg o png?

Me preguntaba cómo convertir Variable-length binary data ( 255216255224016747073700110010100255 ) a un jpeg o png al navegador web.

Código de ejemplo:

 var Connection = require('tedious').Connection; var config = { "userName": "user@server.database.windows.net", "password": "pswd", "server": "server.database.windows.net", "options": { "database": "db", "encrypt": true, } }; var connection = new Connection(config); connection.on('connect', function(err) { console.log("Connected"); } ); var Request = require('tedious').Request; var result, resG; function sendResponse() { var vals; // Convert to string then array var resultA = result.toString().split(','); // Now I can loop through the data returned resultA.forEach(function(val, index, ar) { if(vals == null) { vals = val; } else { vals += val; } }); resG.writeHead(200, {'Content-Type': 'text/html', 'Content-Length': vals.length}); //console.log(vals); //resG.end(""); // Output data returned from db as string resG.end("" + vals); } function executeStatement() { request = new Request("SELECT Photos FROM dbo.tbl WHERE FarmerFirstName='someName' AND FarmerLastName='someLastName'", function(err, rowCount) { if (err) { console.log(err); } else { console.log(rowCount + ' rows'); } }); request.on('row', function(columns) { columns.forEach(function(column) { result = column.value; }); }); request.on('doneInProc', function(rowCount, more) { // Got everything needed from db move on to sending a response sendResponse(); }); connection.execSql(request); } var http = require('http'), director = require('director'); var router = new director.http.Router({ "/": { get: executeStatement } }); var server = http.createServer(function (req, res) { // set global res var resG = res; router.dispatch(req, res, function (err) { if (err) { res.writeHead(404); res.end(); } }); }); server.listen(80); 

Estoy usando tedioso para mi conector db y director como mi enrutador.

El result ya es una matriz de bytes para la imagen. No necesitas hacer ninguna transformación elegante en ello. Esto debería funcionar.

 function sendResponse() { resG.writeHead(200, {'Content-Type': 'image/jpeg', 'Content-Length': result.length}); resG.end(new Buffer(result)); } 

o si quieres servirlo como parte de una página HTML, esto:

 function sendResponse() { resG.writeHead(200, {'Content-Type': 'text/html'}); var vals = (new Buffer(result)).toString('base64') resG.end("" + "" + ""); } 
Intereting Posts