This chapter explored how to write socket-based networked applications in Node. We developed both ends of a server/client interaction and created a JSON-based protocol for them to communicate.
When our assumptions about the protocol began to fail us, we developed a test case to expose the problem. You wrote a custom Node.js module that extended EventEmitter, a core Node.js class. You also learned one technique for buffering streamed data and incrementally scanning it for messages.
Using npm, you installed Mocha, a popular test framework, and used it to develop a unit test.
Writing simple networked applications in Node.js, like those in this chapter, doesn’t take very much code. After only a few lines, you have a functioning server or client application.
However, writing robust applications is harder when you consider the many ways in which a networked application might fail. In the next chapter, we’ll use high-performance messaging libraries and infrastructure to take our Node.js applications to the next level.
The following tasks ask you to improve the code from this chapter, making it more testable and more robust.
In this chapter, we developed a unit test to run with Mocha. Currently it only tests one behavior of the LDJClient class, namely that it emits a message event for a message that came in as a single data event.
The following questions ask you to think about and implement additional tests.
Add a unit test for a single message that is split over two (or more) data events from the stream.
Add a unit test that passes in null to the LDJClient constructor and asserts that an error is thrown. Then make the test pass by modifying the constructor.
The LDJClient developed in this chapter is somewhat fragile. The questions in this section ask you to expand on its implementation in key ways.
The LDJClient already handles the case in which a properly formatted JSON string is split over multiple lines. What happens if the incoming data is not a properly formatted JSON string?
Write a test case that sends a data event that is not JSON. What do you think should happen in this case?
What happens if the last data event completes a JSON message, but without the trailing newline?
Write a case where the stream object sends a data event containing JSON but no newline, followed by a close event. A real Stream instance will emit a close event when going offline—update LDJClient to listen for close and process the remainder of the buffer.
Should LDJClient emit a close event for its listeners? Under what circumstances?