Anyone knows what the status of Web Worker support in NodeJS is? I found a two year old implementation, node-webworkers, but it didn't run with the current build of NodeJS.
Now there is https://github.com/audreyt/node-webworker-threads which appears to be actively maintained.
Worker Threads reached stable status in 12 LTS. Usage example
const {
Worker, isMainThread, parentPort, workerData
} = require('worker_threads');
if (isMainThread) {
module.exports = function parseJSAsync(script) {
return new Promise((resolve, reject) => {
const worker = new Worker(__filename, {
workerData: script
});
worker.on('message', resolve);
worker.on('error', reject);
worker.on('exit', (code) => {
if (code !== 0)
reject(new Error(`Worker stopped with exit code ${code}`));
});
});
};
} else {
const { parse } = require('some-js-parsing-library');
const script = workerData;
parentPort.postMessage(parse(script));
}
You can use the child processes, they solve similar problems.
You can look at the specifics of the HTML5 WebWorker source.
With a little care, you can 'redress' the WebWorker to fit as a Node.js worker, by adding a prelude that may look something like this:
const { parentPort } = require('worker_threads')
global.postMessage = function(msg){
parentPort.postMessage(msg)
}
var handler
global.addEventListener = function(kind, callback){
handler = callback
}
parentPort.on('message', msg => {
handler(msg)
})
The specific HTML5 worker added a message event handler using addEventListener, so I registered such a function in global and saved the handler. I also had to supply a postMessage implementation. Finally I registered a Node.js message handler that invokes the HTML5 handler.
Everything works perfectly. No need for any special dependency, just looking at the HTML5 worker code and identify the points where it deals with messages.
Related
Is there any way to port a complete Web App (which is already responsive and fully compatible with small screens, already has touch UI controls, etc.) to Android/iOS?
My Web App is barebone HTML/JS/CSS, so is super vanilla (I don't even use jQuery).
I thought I could just smash my web app into an empty Ionic-Cordova project and be good with it, but I was wondering is there is a faster/better way to do this?
Maybe a tool or service i don't know about that takes as input a folder and pops out an android/IOS executable?
You can make a PWA (Progressive Web App).
Progressive Web Apps (PWAs) are modern, high quality applications built using web technology. PWAs offer similar capabilities to iOS/Android/desktop apps, they are reliable even in unstable network conditions, and are installable making it easier for users to find and use them.
Basically you have to add a manifest file in .json to your project root where you'll inform many things about your App like icon, name, main color, display mode (choose standalone if you want it to be like an real app) and etc...
(see it here: https://web.dev/add-manifest/) and link to your project pages:
<link rel="manifest" href="/manifest.json">
After that you have to make it installable (https://web.dev/codelab-make-installable/), to do that you will need a service-worker script in your project, you can get one here (https://glitch.com/edit/#!/make-it-installable?path=service-worker.js%3A1%3A0)
const CACHE_NAME = 'offline';
const OFFLINE_URL = 'offline.html';
self.addEventListener('install', function(event) {
console.log('[ServiceWorker] Install');
event.waitUntil((async () => {
const cache = await caches.open(CACHE_NAME);
// Setting {cache: 'reload'} in the new request will ensure that the response
// isn't fulfilled from the HTTP cache; i.e., it will be from the network.
await cache.add(new Request(OFFLINE_URL, {cache: 'reload'}));
})());
self.skipWaiting();
});
self.addEventListener('activate', (event) => {
console.log('[ServiceWorker] Activate');
event.waitUntil((async () => {
// Enable navigation preload if it's supported.
// See https://developers.google.com/web/updates/2017/02/navigation-preload
if ('navigationPreload' in self.registration) {
await self.registration.navigationPreload.enable();
}
})());
// Tell the active service worker to take control of the page immediately.
self.clients.claim();
});
self.addEventListener('fetch', function(event) {
// console.log('[Service Worker] Fetch', event.request.url);
if (event.request.mode === 'navigate') {
event.respondWith((async () => {
try {
const preloadResponse = await event.preloadResponse;
if (preloadResponse) {
return preloadResponse;
}
const networkResponse = await fetch(event.request);
return networkResponse;
} catch (error) {
console.log('[Service Worker] Fetch failed; returning offline page instead.', error);
const cache = await caches.open(CACHE_NAME);
const cachedResponse = await cache.match(OFFLINE_URL);
return cachedResponse;
}
})());
}
});
Just add and save it in .js file in your project.
After that make sure you register the service worker using that code in your project:
/* Only register a service worker if it's supported */
// Service Worker
window.addEventListener('load', () => {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js');
}
});
Now you can make your site installable via some <button> element for example:
window.addEventListener('beforeinstallprompt', (event) => {
// Get the event first
window.deferredPrompt = event;
});
document.querySelector('#buttonInstall').addEventListener('click', () => {
const promptEvent = window.deferredPrompt;
if (! promptEvent) {
return;
}
promptEvent.prompt();
promptEvent.userChoice.then((result) => {
window.deferredPrompt = null;
});
}
});
You can hide the install button when people are in your PWA this way:
if (! window.matchMedia('(display-mode: standalone)').matches) {
// hide your install button
}
Here is some important things:
Your app have to meets certain criteria to be installable, you can
see it here: https://web.dev/install-criteria/
If the install pop-up doesn't appear, it means you made something
wrong, or your manifest is broken or your script.
You can see if your manifest.json is ok in browser developer tools open it (F12), go to Application tab and go to Manifest, this will show all your manifest parameters and it will show if something is wrong too.
I recommend you to read all the links above, there is a lot more
details an explanation about PWAs
simple way to port web app to mobile app is to make a WebView app in android. then give it your web app link address
I'm trying to call an injected HttpClient during operations within a Razor Component. When I do so during OnInitialized, the return is as expected. When I do so on an event like an input change, the client call doesn't respond.
I'm using a mix of MVC Controllers/Views with Razor Components in .Net Core 3.1.
Startup.cs
services.AddControllersWithViews()...
services.AddRazorPages()...
services.AddHttpClient<IJiraService, JiraService>("jira", c =>
{
c.BaseAddress = new Uri(Configuration.GetSection("ApplicationSettings:Jira:Url").Value);
var auth =
$"{Configuration.GetSection("ApplicationSettings:Jira:UserName").Value}:{Configuration.GetSection("ApplicationSettings:Jira:Password").Value}";
var authHeaderValue = Convert.ToBase64String(Encoding.UTF8.GetBytes(auth));
c.DefaultRequestHeaders.AddAuthorization("Basic", authHeaderValue);
c.Timeout = TimeSpan.FromSeconds(20);
c.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue
{
NoCache = true
};
});
ChildComponent.razor
#inject IJiraService JiraService
#code {
public int SelectedReleaseId
{
get => ReleaseModel.SelectedReleaseId;
set
{
ReleaseModel.SelectedReleaseId = value;
ReleaseChanged().Wait();
}
}
}
#functions
{
private async Task ReleaseChanged()
{
if (ReleaseModel.SelectedReleaseId > 0)
{
var url = "...";
await JiraService.GetResponseAsync(url);
}
}
JiraService.cs
public async Task<string> GetResponseAsync(string url)
{
var resp = await httpClient.GetAsync(url); // <--- this is the call that never returns when invoked from an input control event
var respContentString = await resp.Content.ReadAsStringAsync();
if (resp.StatusCode != HttpStatusCode.OK)
{
throw new HttpOperationException(
$"Invalid response from Jira service: {resp.StatusCode}: {respContentString}");
}
return respContentString;
}
There's actually a bit of service classing in between, but this is the jist.
I've abstracted the call up to a parent component and implemented EventCallbacks all with the same result. The underlying call in the JiraService gets hit and i see a breakpoint stop on the await httpClient.GetAsync(url); but then execution just goes into the ether. There's not even an exception thrown or timeout.
It all seems so obvious now. The problem was a deadlock. This old post helped me realize that my property based #bind attribute was synchronously calling into an async/await graph. I refactored this into an #onchange function that enabled appropriate async/await behavior through the call stack and viola, await httpClient.GetAsync() behaved just like it should.
A little annoyed at the #bind behavior that takes the onchange event functionality in addition to the property value.
I built a website that uses the Chrome web midi interface (based on navigator.requestMidiAccess) that works fine in a local development server, but when pushed to a cloud server fails, saying that navigator.requestMidiAccess is not a function. The same code, the same browser. I'll try to include the relevant code:
function initializeMidi() {
navigator.requestMIDIAccess()
.then(
(midi) => midiReady(midi),
(err) => console.log('Something went wrong', err));
}
window.onload = (event) => {
initializeMidi();
};
// this next function builds a list of radio buttons to select the MIDI device
function midiReady(midi) {
globalMidi = midi.outputs
parentElement = document.getElementById('midi-devices-div')
parentElement.innerHTML = ''
var lastMidiPortName = null
midi.outputs.forEach(function (port, key) {
addRadioButton(parentElement, port)
lastMidiPortName = port.name
})
var n = window.localStorage.getItem('selectedMidiPortName')
if (n)
{
var e = document.getElementById(n)
e.checked = true
}
}
The Web MIDI interface is only exposed to SecureContexts, you must serve your document using https://.
I use Bluebird 3 with enabled cancellation. Is cancellation the tool to use in the following use case:
var resourcesPromise = Promise.map(resourceIds, function(id) {
return loadResource(id);
});
resourcesPromise.catch(function() {
resourcesPromise.cancel();
});`
If one of the resources fails to load, resourcesPromise will be rejected, and I want to stop the loading of all other resources. But as far as I can tell, cancelling resourcesPromise doesn't work, because it is already rejected.
Edit: I'm currently considering variants of the following:
var resourcesPromise = new Promise(function(resolve, reject) {
var intermediatePromise = Promise.map(resourceIds, function(id) {
return loadResource(id).catch(function(error) {
intermediatePromise.cancel();
reject(error);
});
}).then(resolve, reject);
});
(I may have found a legitimate use for the ".then(resolve, reject)" anti-pattern!)
Any ideas why Promise.map doesn't work like that?
With map you are parallelizing the resource loading, maybe is better to use Promise.each to laoad resources in sequence. In such case you don't need to cancel the promise to stop loading the remaining resources when one fails.
var resourcesPromise = Promise.map(resourceIds, function(id) {
return loadResource(id);
});
resourcesPromise.catch(function() {
resourcesPromise.cancel();
});`
Another option would be to pass to the map function an option object like in which you can specify the concurrency limit.
Promise.resolve(resourceIds).
map(function(id) {
return loadResource(id);
}, {concurrency: n}).
catch(function(e) {
//do some error handling
});
I'm just learning angularJS (using angular-seed) and I need to load my site config from a JSON feed before the rest of the site loads.
Unfortunately, using $http or $resource doesn't return the feed in time for the rest of the app to load.
What is the correct way to force the app to load this data before the rest of the app?
You have to use the Controller.resolve method. Check out Misko's (one of the core Angular developer) answer https://stackoverflow.com/a/11972028/726711
Using the resolve method broke all my unit tests... I went with this way, where settings is a service.
$q.when(settings.loadConfig()).then(function () {
console.log( settings.versionedApiUrl );
});
Then, i check if we've already loaded settings to make sure we don't request more than once.
class settings {
loadConfig = ( ):angular.IPromise<any> => {
var deferred = this.q.defer();
if( this.settingsLoaded ){
deferred.resolve({})
return deferred.promise;
}
this.http({
url:'config.json'
}).then((result) => {
if( result.data ){
this.versionedApiUrl = result.data.versionedApiUrl;
this.apiServer = result.data.apiServer;
this.widgetServiceRoot = result.data.widgetServiceRoot;
this.settingsLoaded = true;
}
deferred.resolve({});
});
return deferred.promise;
}
}