Skip to content

Instantly share code, notes, and snippets.

@jacob-ebey
Last active June 27, 2021 05:15
Show Gist options
  • Save jacob-ebey/c5f35ced139c5fc8ca02b02c3d6883d9 to your computer and use it in GitHub Desktop.
Save jacob-ebey/c5f35ced139c5fc8ca02b02c3d6883d9 to your computer and use it in GitHub Desktop.
React18 renderToStringWithWritable
const { PassThrough } = require('stream');
const { pipeToNodeWritable } = require('react-dom/server');
function renderToStringWithWritable(element, timeout = 10000) {
return new Promise((resolve, reject) => {
const writable = new PassThrough();
let res = '';
writable.on('data', d => {
res += String(d);
});
writable.on('end', function() {
resolve(res);
});
const { startWriting, abort } = pipeToNodeWritable(element, writable, {
onCompleteAll() {
writable.write('<!DOCTYPE html>');
startWriting();
},
onError(err) {
reject(err);
}
});
setTimeout(abort, timeout);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment