Code Monkey home page Code Monkey logo

pipe's Introduction

@jongleberry/pipe

Node.js CI codecov

Streaming and async template rendering for node.js using template strings. Define variables or sections as promises or streams or thunks that return either in your template, and they will be evaluated at render time.

This allows you to create fast, non-blocking server-side rendered applications while minimizing time-to-first-byte for the user.

Example

const pipe = require('@jongleberry/pipe')

const render = function ({
  currentUser
}) {
  return pipe`
    <!DOCTYPE html>
    <html>
      <head>
        <title>Example</title>
        <link rel='stylesheet' href='entrypoint.css'>
      </head>
      <body>
        ${async () => React.renderToNodeStream(React.createElement(App, {
          currentUser: await currentUser,
        }))}
        <script>window.__INITIAL_STATE__ = ${async () => JSON.stringify({
          currentUser: await currentUser,
        })}
        <script src='entrypoint.js></script>
      </body>
    </html>
  `
}

// express middleware
function (req, res) {
  res.setHeader('content-type', 'text/html; charset=utf-8')
  res.flushHeaders()

  render({
    // pass a promise that resolves to the user
    getCurrentUser: services.getCurrentUser(req)
  }).pipe(res)
}

API

stream = pipe`` || pipe(strings, ...values)

render is a tagged template that returns a readable PassThrough stream.

Value Types

  • <String> - serialize anything that isn't a string yourself as this library will throw.
  • Promise<String> - a promise that returns a string.
  • Stream - a binary stream that will be pipe directly into the response. This library does not check its contents, but object streams will throw: pipe it into a stream such as streaming-json-stringify.
  • A function or async function that returns either of the above.

Error Handling

Any section of the template that errors will simply not be rendered. Streams may partially be rendered, so it's advised that you handle stream errors yourself or pass streams that cannot error (e.g. a passthrough stream). Listen to any errors on the resulting stream, e.g.:

const stream = pipe`<div id="root">${async () => React.renderToNodeStream(React.createElement(App, { 
  currentUser: await currentUser 
}))}</div>`
stream.on('error', err => console.error(err.stack))

Some frameworks such as Koa automatically handle this when you set the stream as ctx.body = stream

Note that because status codes (or should be) flushed to the client before rendering begins, errors in the template cannot affect the response status code.

Implementation Notes

Alternatives

Please let me know if you are aware of any other ones.

pipe's People

Contributors

dependabot-preview[bot] avatar dependabot[bot] avatar jonathanong avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Forkers

sausawmg

pipe's Issues

Alternatives

Thanks for the library -- exactly what I needed!

Please let me know if you are aware of any other ones.

Here's a very similar one, albeit in TS: https://github.com/kitten/stream-tag

On a side note, I found the name 'pipe' to be confusing -- have you considered alternative names for this library?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.