2K01B5
2K01B5

Reputation: 1121

How to know what encoding to use when reading files?

When reading an image file what encoding should I be using? I'm building a basic server to serve up a html file with an image and when I read the image file with the encoding of 'utf-8' and send the data to the browser, the browser doesn't receive the image. However, if I set the encoding to an empty string(i.e. {encoding: ''}), the browser receives the image. Also, when I look at the read stream object it says that the default encoding is 'utf-8', which makes me wonder why setting the encoding to 'utf-8' doesn't work?

Here's the piece of code that doesn't work:

let readStream = fs.createReadStream('./static/002.jpg', {flags: 'r', encoding: 'utf8'})
    console.log('ReadStream: ',  readStream)
    res.setHeader('Content-Type', 'image/jpeg')
    readStream.on('data', (chunk) => {
        res.write(chunk)
    })

    readStream.on('error', (err) => {
        console.log(err)
    })

    readStream.on('end', () => {
        console.log('Image stream ended')
        res.end()
    })

    readStream.on('close', function(){
        console.log("Image Stream closed")
    })

And here's the piece of code that does work:

let readStream = fs.createReadStream('./static/002.jpg', {flags: 'r', encoding: ''})
        console.log('ReadStream: ',  readStream)
        res.setHeader('Content-Type', 'image/jpeg')
        readStream.on('data', (chunk) => {
            res.write(chunk)
        })

    readStream.on('error', (err) => {
        console.log(err)
    })

    readStream.on('end', () => {
        console.log('Image stream ended')
        res.end()
    })

    readStream.on('close', function(){
        console.log("Image Stream closed")
    })

Upvotes: 1

Views: 5132

Answers (1)

jhkouy78reu9wx
jhkouy78reu9wx

Reputation: 342

The reason is that JPEG image is a binary file, which means that it is a sequence of plain bytes. encoding setting is used when reading text files. if you don't specify encoding or pass null, you'll get a raw stream of bytes, that is exactly what you need to transfer binary data.

Documentation for a Readable Stream says that if no encoding is provided, Buffer object is returned instead of string. This is the reason why default buffer encoding utf8 is not applied.

See for additional info:

  1. Node.js v8.5.0 Documentation: Buffers and Character Encodings

Upvotes: 3

Related Questions