streamsaver
Version:
StreamSaver writes stream to the filesystem directly - asynchronous
49 lines (41 loc) • 1.64 kB
HTML
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<button id="$start">Start</button>
<script src="https://cdn.jsdelivr.net/npm/web-streams-polyfill@2.0.2/dist/ponyfill.min.js"></script>
<!-- includes blob.stream() polyfill -->
<script src="https://cdn.jsdelivr.net/gh/eligrey/Blob.js/Blob.js"></script>
<script src="../StreamSaver.js"></script>
<script src="zip-stream.js"></script>
<script>
// Saving a blob is as simple as the fetch example, you just get the
// readableStream from the blob by calling blob.stream() to get a
// readableStream and then pipe it
// One alternetive way of getting the stream is by doing:
// const readableStream = new Response(blob).body
$start.onclick = () => {
const fileStream = streamSaver.createWriteStream('sample.txt')
const blob = new Blob(['StreamSaver is awesome'])
const readableStream = blob.stream()
// more optimized pipe version
// (Safari may have pipeTo but it's useless without the WritableStream)
if (window.WritableStream && readableStream.pipeTo) {
return readableStream.pipeTo(fileStream)
.then(() => console.log('done writing'))
}
// Write manually
window.writer = fileStream.getWriter()
const reader = readableZipStream.getReader()
const pump = () => reader.read()
.then(res => res.done
? writer.close()
: writer.write(res.value).then(pump))
pump()
}
</script>
</body>
</html>