'Using subtle in a Javascript module, from both the browser and NodeJS
NodeJS has an experimental implementation of the browser's crypto.subtle.
I have written a Javascript module which runs in both the browser and the NodeJS. It needs access to subtle.
For the moment, every function which needs to use subtle awaits the following function at the beginning of execution:
async function getSubtle() {
if (typeof window === 'undefined') { // running in NodeJS
const crypto = await import('crypto');
return crypto.webcrypto.subtle;
} else { // running in a browser
return crypto.subtle;
}
}
This works, but is slow and ugly as I'm re-importing the code on every function call (in NodeJS).
My project is simple enough that I do not use a build system. (I use express and symlink the modules I require, e.g. from public/js/modules/foo.mjs to lib/foo.js.)
Can I replace getSubtle() with a module-level non-async conditional import? If so, how?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
