E
E
Emptyform2016-08-24 18:28:16
Node.js
Emptyform, 2016-08-24 18:28:16

Error when working with fs.ReadStream: getting empty data on last on('readable'). Why?

Hey!
Code (training):

'use strict';

let fs = require('fs');

module.exports = (res, filePath) => {
    let stream = new fs.ReadStream(filePath);
    stream
        .on('readable', () => {
            console.log('on readable');
            let data = stream.read();
            res.write(data);        // <=== здесь ошибка
        })
        .on('end', () => {          // <-- сюда не заходит
            console.log('on end');
            res.end('');
        })
        .on('close', () => {        // <-- сюда не заходит
            console.log('on close');
        })
        .on('error', (err) => {     // <-- сюда не заходит
            console.log('on error :: ' + err.code + '; ' + err.message);
            res.statusCode = 400;
            res.end('Bad request');
        })
    ;
};

CASE 1:
I pass the name of a file with a picture to the input, the picture is rendered on the client, and the server crashes with the text "First argument must be a string or Buffer" and points to the string res.write(data); - there indeed, in the last readable event, the stream.read() function ; returns null
My questions are:
1.1 - why did readable work if there is no data? (it is clear that you can write if (data) res.write(data); but this is a crutch, it seems to me)
1.2 - why on('error') did not catch the error?
1.3 - why didn't on('close') work?
1.4 - how to properly protect yourself from such errors, where to intercept them so that the server does not crash?
CASE 2:
I pass to it a text file encoded windows-1251 on the screen - squiggles. When opening the stream, I tried to specify {encoding: 'windows-1251'} as the second parameter Result: Unknown encoding: windows-1251
2.1 - where can I find a list of values ​​for encoding for different encodings?
2.2 - is it possible to somehow find out the encoding of a text file while the script is running?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question