Created
January 21, 2018 06:57
-
-
Save zapkub/4dbe3a002d875c725fc94e2c329c781d to your computer and use it in GitHub Desktop.
http stream with nodejs express
This file contains hidden or 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
// on client request | |
const xhr = new XMLHttpRequest() | |
// request to api endpoint | |
xhr.open('post', '/documents.zip') | |
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8') | |
xhr.onprogress = () => { | |
// receive stream | |
console.log('PROGRESS:', xhr.responseText) | |
// split data on stream | |
const res = (xhr.responseText.toString().split('|')) | |
const result = JSON.parse(res[res.length-1]) | |
// if streaming done when url available | |
if(result.url) { | |
result.isPrepare = false | |
} | |
// update react state | |
this.setState({ | |
...result | |
}) | |
} | |
xhr.send( | |
JSON.stringify({ | |
ids | |
}) | |
) |
This file contains hidden or 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
// express handler function | |
// setup header | |
res.setHeader('X-Content-Type-Options', 'nosniff') | |
res.setHeader('Content-Type', 'text/plain') | |
res.setHeader('Transfer-Encoding', 'chunked') | |
// write first data to response stream | |
res.write( | |
JSON.stringify({ | |
current: 0, | |
total: results.length | |
}) | |
) | |
for (let info of results) { | |
// do something async..... ( in this case render multiple pdf file ) | |
console.log('generate....', info._id) | |
const path = await renderFormToPDF(info, folderName + '/files') | |
fileList.push(path) | |
// continue write data on stream | |
res.write( | |
'|' + | |
JSON.stringify({ | |
current: fileList.length, | |
total: results.length | |
}) | |
) | |
} | |
// end of stream return url data to client | |
res.write( | |
'|' + | |
JSON.stringify({ | |
url: folderAbsolute + '/documents.zip' | |
}) | |
) | |
res.end() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment