Last active
June 27, 2021 05:15
-
-
Save jacob-ebey/c5f35ced139c5fc8ca02b02c3d6883d9 to your computer and use it in GitHub Desktop.
React18 renderToStringWithWritable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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