Welcome to the Linux Foundation Forum!

How to force the `finished` function to be called?

In the lesson "Determining End-of-Stream" we have an implementation using the finished function with the socket stream.

According the explanation, "The stream (socket) is passed to finished as the first argument and the second argument is a callback for when the stream ends for any reason. The first argument of the callback is a potential error object. If the stream were to emit an error event the callback would be called with the error object emitted by that event."

If I understood it correctly, if there is an error emited by the socket, the finished function should be executed. Then **how can I force an error to test it? **

Answers

  • anthonycd
    anthonycd Posts: 3
    edited May 30

    Hi Paulo,

    In order to test a solution could be to write a custom string from the client socket, then on the server socket, in the data event listener, get the data and check If the value match with your custom string, if it's the case you can trigger an error in the server socket by calling the destroy method on the socket or by emitting an error event for example.
    This will cause the finished method to pass the error as argument of the callback.

    Hope this help🙏.

  • Hey @anthonycd thank you for you response.
    I tried this approach you suggested - throwing the Error('all done') - with the code bellow:

    net.createServer((socket) => {
        const interval = setInterval(() => {
            socket.write('beat')
        }, 1000)
        socket.on('data', (data) => {
            if (data.toString() === 'all done') {
                throw Error('all done')
            }
            socket.write(data.toString().toUpperCase())
    
        })
        finished(socket, (err) => {
            console.log('FINISHED!!')
            if (err) {
                console.error('there was a socket error', err)
            }
            clearInterval(interval)
        })
    }).listen(3000)
    

    Note that the finished function has a console.log, but the error "leaks" and crashed the app, and the output, does not show the message "FINISHED!!", that should have been logged. Take a look here:

    user@xxx-computer exercises % node end-of-stream/index.js
    /xxx-path/labs.node-v20/ch-12/exercises/end-of-stream/index.js:14
    throw Error('all done')
    ^

    Error: all done
    at Socket. (/xxx-path/labs.node-v20/ch-12/exercises/end-of-stream/index.js:14:19)
    at Socket.emit (node:events:514:28)
    at addChunk (node:internal/streams/readable:376:12)
    at readableAddChunk (node:internal/streams/readable:349:9)
    at Readable.push (node:internal/streams/readable:286:10)
    at TCP.onStreamRead (node:internal/stream_base_commons:190:23)

    Node.js v20.9.0

    I assume this implementation is not right, but I did not find a proper one online.

    Thanks once again.

  • anthonycd
    anthonycd Posts: 3
    edited May 30

    Hi @paulo.barbeiro ,

    Instead of throwing the error, you should call the destroy() method on the socket, which will allow Node.js internals to properly pass the error to the finished() method. If you throw an error, you need to wrap the logic of checking the value of the data with a try/catch block. The callback of the data event listener will be called asynchronously, but the error will be thrown synchronously, resulting in an exception. Unfortunately, using a try/catch block will add unnecessary complication to your implementation, and the error thrown won't be passed to the finished() method.

  • anthonycd
    anthonycd Posts: 3

    Emitting an error event on the socket instead of calling the destroy() method will also work fine.

  • Thanks @anthonycd!

    Yes, after reading your first message, I also try the "return Error" and it worked. Here is the implementation:

    net.createServer((socket) => {
        const interval = setInterval(() => {
            socket.write('beat')
        }, 1000)
        socket.on('data', (data) => {
            if (data.toString() === 'all done') {
                // throw Error('all done') // Crashes the app: fails the implementation
                return Error('all done') // Works just fine. Thanks anthonycd for the reminder of teh callbacks logic
                // socket.destroy() // Also works. Thanks anthonycd for this solution
            }
            socket.write(data.toString().toUpperCase())
    
        })
        finished(socket, (err) => {
            console.log('FINISHED!!')
            if (err) {
                console.error('there was a socket error', err)
            }
            clearInterval(interval)
        })
    }).listen(3000)
    
  • xdxmxc
    xdxmxc Posts: 157

    nicely andwered @anthonycd - the misunderstanding here was that throwing in an event listener causes the stream to error, but it doesn't.

Categories

Upcoming Training