4

i want to convert png image from buffer to string, and then convert string to buffer.

fs.readFile('/Users/xxx/Desktop/1.png', (err, data) => {
    if (err) throw err; // Fail if the file can't be read.
    data = Buffer.from(data)
    let str = data.toString()
    data = Buffer.from(str)
});

// server
router.register('/api/dump', (request, response) => { 
    fs.readFile('/Users/xxx/Desktop/1.png', (err, data) => {
        if (err) throw err; // Fail if the file can't be read. 
        response.writeHead(200, {'Content-Type': 'image/jpeg'}); 
        response.end(data); // Send the file data to the browser.
    });
}) 

// front
this.$get('/dump').then(result => {
    // i want to convert result to buffer
})

but the new buffer is not old buffer any more.

2218
  • 41
  • 1
  • 1
  • 4
  • What's the problem with the router code?, there's nothing wrong with it, it has nothing to do with the original question nor with the snippet above it. – Marcos Casagrande Apr 03 '19 at 02:55

1 Answers1

6

Buffer.toString() default encoding is utf8, and you can't convert from utf8 back to Buffer without breaking the image.

If you want to convert to string, and then back to buffer, you will need to use an encoding that allows this, for example base64.

fs.readFile('/Users/yihchu/Desktop/1.png', (err, data) => {
    if (err) throw err; // Fail if the file can't be read.
    var oldData = data;
    let str = data.toString('base64')
    data = Buffer.from(str, 'base64');
});
Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98
  • i wrote a server using nodejs, code is: router.register('/api/dump', (request, response) => { fs.readFile('/Users/yihchu/Desktop/1.png', (err, data) => { if (err) throw err; // Fail if the file can't be read. response.writeHead(200, {'Content-Type': 'image/jpeg'}); response.end(data); // Send the file data to the browser. }); }) and the response that web page received is just like toString in utf8, i want to convet it to buffer – 2218 Apr 03 '19 at 02:31
  • Put that in code block, in your original question, so it can be read. – Marcos Casagrande Apr 03 '19 at 02:40
  • What is it you're trying to achieve, it seems your problem is something else. – Marcos Casagrande Apr 03 '19 at 03:02
  • this.$get('/dump').then(result => { // i want to convert result to buffer }) the result is just like Buffer.toString('utf8'), and i want to conver to back to buffer – 2218 Apr 03 '19 at 03:29
  • why, why do you need the buffer on the front end, explain what you're trying to achieve, not just "I want to convert to buffer", Why do you need the buffer. – Marcos Casagrande Apr 03 '19 at 04:01