Skip to content

Implement the serializer #5

@matthewp

Description

@matthewp

Referring to the API issue you can see that the serializer module should be used like so:

var stream = serialize(element);
stream.pipe(response);

This means our serialize function needs to return a stream. The type of stream we will create is a Readable stream.

Make the module return a stream

Update src/vdom-streaming-serializer.js to look like this:

var Readable = require('stream').Readable;

module.exports = function(element){
  var stream = new Readable();
  stream._read = function(){
    // This is where we start doing stuff
  };
  return stream;
};

This makes our module implement the API it is supposed to... it just doesn't do anything yet. We'll do that later.

Update the demo script

Back in the demo script you created earlier, update it to read from the stream:

var stream = serialize(document.documentElement);

stream.on('data', function(chunk){
  // This is a chunk of HTML!
  console.log(chunk);
});

stream.on('end', function(){
  // All HTML has been written
});

Now you've created a stream, it just never fires events. The next step is to do the hard work of implementing the streaming serializer.

Making the serializer work

Keys here are:

  1. We want to create HTML strings so we need:
    • The tag name (element.localName)
    • Its attributes (which you can loop over with element.attributes)
    • Its children (which you can loop over with element.childNodes)
  2. When you come to a Node (either an attribute, element, or text) that is marked as Symbol.for('async-node') you need to stop.
  3. Flush the current html string parts when you hit an async node.
  4. When the async node results, continue where you left off.
  5. The async node might have been replaced, so keep a reference to the parent and the position that your node sits.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions