Your code doesn't work for binary files because they can't be cast to strings in the data event handler. If you need to manipulate binary files you'll need to use a buffer. Sorry, I do not have an example of using a buffer because in my case I needed to manipulate HTML files. I just check the content type and then for text/html files update them as needed:
app.get('/*', function(clientRequest, clientResponse) {
var options = {
hostname: 'google.com',
port: 80,
path: clientRequest.url,
method: 'GET'
};
var googleRequest = http.request(options, function(googleResponse) {
var body = '';
if (String(googleResponse.headers['content-type']).indexOf('text/html') !== -1) {
googleResponse.on('data', function(chunk) {
body += chunk;
});
googleResponse.on('end', function() {
// Make changes to HTML files when they're done being read.
body = body.replace(/google.com/gi, host + ':' + port);
body = body.replace(
/<\/body>/,
'<script src="http://localhost:3000/new-script.js" type="text/javascript"></script></body>'
);
clientResponse.writeHead(googleResponse.statusCode, googleResponse.headers);
clientResponse.end(body);
});
}
else {
googleResponse.pipe(clientResponse, {
end: true
});
}
});
googleRequest.end();
});