Skip to content

Instantly share code, notes, and snippets.

@timfish
Last active November 3, 2021 00:29
Show Gist options
  • Save timfish/a79becf27f5df00a2a641bb83330f84b to your computer and use it in GitHub Desktop.
Save timfish/a79becf27f5df00a2a641bb83330f84b to your computer and use it in GitHub Desktop.
Protocol JSON stream to renderer
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
We are using Node.js <span id="node-version"></span>,
Chromium <span id="chrome-version"></span>,
and Electron <span id="electron-version"></span>.
<!-- You can also require other files to run in this process -->
<script src="./renderer.js"></script>
</body>
</html>
// Modules to control application life and create native browser window
const { app, BrowserWindow, protocol, session } = require('electron')
const path = require('path')
const { Readable } = require('stream');
protocol.registerSchemesAsPrivileged([{
scheme: 'testing',
privileges: { bypassCSP: true, supportFetchAPI: true }
}]);
function registerProtocol() {
session.defaultSession.protocol.registerStreamProtocol('testing', (request, callback) => {
const stream = new Readable({
read(size) { },
});
setInterval(() => {
stream.push(JSON.stringify(app.getAppMetrics()) + '\n')
}, 5000);
callback({
statusCode: 200,
data: stream
})
});
}
function createWindow() {
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
mainWindow.loadFile('index.html')
mainWindow.webContents.openDevTools({ mode: 'detach' })
}
app.whenReady().then(() => {
registerProtocol()
createWindow()
})
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
{
"name": "unhappy-market-cause-hoqc7",
"productName": "unhappy-market-cause-hoqc7",
"description": "My Electron application description",
"keywords": [],
"main": "./main.js",
"version": "1.0.0",
"author": "tim",
"scripts": {
"start": "electron ."
},
"dependencies": {},
"devDependencies": {
"electron": "15.3.0"
}
}
// All of the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.
window.addEventListener('DOMContentLoaded', () => {
const replaceText = (selector, text) => {
const element = document.getElementById(selector)
if (element) element.innerText = text
}
for (const type of ['chrome', 'node', 'electron']) {
replaceText(`${type}-version`, process.versions[type])
}
})
// copied from can-ndjson-stream
var ndjsonStream = function (response) {
// For cancellation
var is_reader, cancellationRequest = false;
return new ReadableStream({
start: function (controller) {
var reader = response.getReader();
is_reader = reader;
var decoder = new TextDecoder();
var data_buf = "";
reader.read().then(function processResult(result) {
if (result.done) {
if (cancellationRequest) {
// Immediately exit
return;
}
data_buf = data_buf.trim();
if (data_buf.length !== 0) {
try {
var data_l = JSON.parse(data_buf);
controller.enqueue(data_l);
} catch (e) {
controller.error(e);
return;
}
}
controller.close();
return;
}
var data = decoder.decode(result.value, { stream: true });
data_buf += data;
var lines = data_buf.split("\n");
for (var i = 0; i < lines.length - 1; ++i) {
var l = lines[i].trim();
if (l.length > 0) {
try {
var data_line = JSON.parse(l);
controller.enqueue(data_line);
} catch (e) {
controller.error(e);
cancellationRequest = true;
reader.cancel();
return;
}
}
}
data_buf = lines[lines.length - 1];
return reader.read().then(processResult);
});
},
cancel: function (reason) {
console.log("Cancel registered due to ", reason);
cancellationRequest = true;
is_reader.cancel();
}
});
};
fetch('testing://stream').then((response) => {
return ndjsonStream(response.body)
}).then(async (exampleStream) => {
const reader = exampleStream.getReader()
while (true) {
const value = await reader.read();
console.log(value.value)
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment