I have been trying to load a WebAssembly (.wasm) file - generated C++ code compiled to WebAssembly by Emscripten - in a React-Native app.
This is my code to fetch the .wasm file:
import fs from 'react-native-fs';
if (!global.WebAssembly) {
global.WebAssembly = require('webassemblyjs');
}
const fetchWasm = async () => {
const wasm = await fetch(`${fs.MainBundlePath}/calculator.wasm`);
console.log(wasm);
// Returns: Response {type: "default", status: 200, ok: true, statusText: undefined, headers: Headers, …}
const mod = await WebAssembly.instantiateStreaming(wasm);
console.log(mod);
// Throws: TypeError: Failed to execute 'compile' on 'WebAssembly': An argument must be provided, which must be a Response or Promise<Response> object
};
I tried everything in the Google search results I could find, but nothing worked so far. Unfortunately, the most related questions were unanswered.
Is there anyone who knows what I am doing wrong? Any help would be greatly appreciated!
There is one thing to be aware when wanting to load wasm :
Your webserver must report .wasm mime type as "application/wasm" , otherwise you won't be able loading it.
I assume still React-native JS runtime JSC still not support WebAssembly in Android build
the issue is still open
https://github.com/react-native-community/jsc-android-buildscripts/issues/113
Another way is to use Webview but I assume it is not you are expecting.
https://github.com/ExodusMovement/react-native-wasm
Related
I am getting this problem every time I import a lib or when I use puppeteer and I don't know how to fix it. I am trying to get some data from LinkedIn using https://www.npmjs.com/package/linkedin-client
the code is easy:
import LinkedinClient from 'linkedin-client';
async function getIt() {
const session = supabase.auth.session();
const tok = session?.provider_token;
const token = JSON.stringify(tok);
console.log(token);
const client = new LinkedinClient(token);
const data = await client.fetch('https://www.linkedin.com/in/some-profile/');
console.log(data);
}
at first it gives me this error:Module "util" has been externalized for browser compatibility. Cannot access "util.promisify" in client code
after I install npm i util then it displays the following error:
500 process is not defined ReferenceError: process is not defined
Can you please let me know how to fix it?(I'm using sveltekit)
The library requires to be run on the server. It has be in a server endpoint, it cannot be in a component or a load function.
If this is already the case, this might be an issue with Vite trying to remove server dependencies. There is e.g. a plugin #esbuild-plugins/node-globals-polyfill which polyfills the process variable. It may also be necessary to list packages in resolve.alias in the Vite config, to point to the Node modules.
I am trying to use #metaplex/js to do some NFT minting. Usually my .js files work properly but when I run the file this error comes up.
bigint: Failed to load bindings, pure JS will be used (try npm run rebuild?)
I don't really get what that means. So, I tried to run npm run rebuild but rebuild is said to be a missing script and I couldn't find a way to install it.
Here is my code:
import { Connection, programs} from "#metaplex/js";
import { Loader } from "#solana/web3.js";
const { metadata: {Metadata}} = programs;
const connection = new Connection("devnet");
const tokenPublicKey = 'my_adress';
const run = async() => {
try{
const ownedMetadata = await Metadata.Loader(connection,tokenPublicKey)
console.log(ownedMetadata)
}
catch{
console.log('Failed to fetch')
}
};
run();
If you have any idea, or simply an explanation of what my error means, I'd be grateful.
You are getting this error because a nested dependency has a compilation step that might not succeed in your platform. This issue provides a good explanation.
[...] This happens because one of our dependencies (bigint-buffer) runs a compilation step on installation and this can step may fail for a couple of reasons. One of the reasons is that your system might not have the build-tools the library is looking for. You can install these build tools on Windows (see https://www.npmjs.com/package/windows-build-tools), but you don't actually need to as it automatically falls back to a pure JS solution instead. Though I agree... that warning is very annoying.
However, this should give you a warning and still allow you to compile your code.
It is worth noting that the current JS SDK from Metaplex is going to be deprecated in favour of the new one: https://github.com/metaplex-foundation/js-next
With the new JS SDK, you can fetch an NFT using the following piece of code.
import { Metaplex } from "#metaplex-foundation/js";
import { Connection, clusterApiUrl } from "#solana/web3.js";
const connection = new Connection(clusterApiUrl("mainnet-beta"));
const metaplex = new Metaplex(connection);
const mintAddress = new PublicKey("ATe3DymKZadrUoqAMn7HSpraxE4gB88uo1L9zLGmzJeL");
const nft = await metaplex.nfts().findByMint({ mintAddress });
Hello
I want to import a .glb file but when I call it in JS I get an error which tell me that the file isn't found whereas the file was copied.
Here's my files:
wwwroot
/-Assets
/---Element
/---Objects3D
/-----hub.glb
Here, the error:
Failed to load resource: the server responded with a status of 404 () :44353/Assets/Objects3D/hub.glb:1
Have you an idea ?
Thank you !
Ok so with some little investigation I was able to solve my issue, this might help you solve your problem too.
In the server side when setting the UseStaticFiles you should add some options to allow UnkownType files to be accessed.
There are two ways you can solve this. The first is especifying the type of the file that you wish to provide that way. In this case you should do it this way on you Startup.cs file, Configure function:
StaticFileOptions options = new StaticFileOptions { ContentTypeProvider = new FileExtensionContentTypeProvider() };
((FileExtensionContentTypeProvider)options.ContentTypeProvider).Mappings.Add(new KeyValuePair<string, string>(".glb", "model/gltf-buffer"));
app.UseStaticFiles(options);
The second option (and more appropriate if you have more than 1 Unkown file type) is to allow any UnkownTypeFile using a flag on the same StaticFileOptions at the same Configure function:
StaticFileOptions options = new StaticFileOptions { ContentTypeProvider = new FileExtensionContentTypeProvider() };
options.ServeUnknownFileTypes = true;
app.UseStaticFiles(options);
Also, make sure you are able to access the subdomain directories on you server. If you are not, then you should also include this in your ConfigureServices function in the Startup.cs file:
services.AddDirectoryBrowser();
As well as the line bellow on your Configure function at the same file:
app.UseFileServer(enableDirectoryBrowsing: true);
Note: This solution is for a server using .Net Core 3.1. If you are using a different version or .Net Framework there might be a different fix.
I am using rotateByDegrees from a library called node-poweredup in a typescript project:
motor.rotateByDegrees(20,10).then(function(value) {console.log("test");}, function(value) {console.log("error");});
I would expect to see "test" after successful completion, but the promise never resolves. If I use await, it hangs on the await line forever.
Replicating the syntax that appears to be used in the rotateByDegrees function:
let promise = new Promise((resolve) => { return resolve(); });
does not compile, I get error TS2794: Expected 1 arguments, but got 0. Did you forget to include 'void' in your type argument to 'Promise'? I can make it compile and behave as expected with resolve(true), but how does it compile in the library then? Do I misunderstand promises? Some feature in typescript? A bug in the library? I am a newbie to JavaScript, I don't want to over-complicate this question by including irrelevant details. If you can give me hints on what I am missing and how to debug this, I can provide all relevant details.
Thanks to the helpful comments I was able to narrow it down to the compilation of the library. I did in fact not use a pre-compiled binary but had to compile the library myself using electron-rebuild to make the bluetooth adapter work. I did the following test:
git clone https://github.com/nathankellenicki/node-poweredup.git
cd node-poweredup
npm install
npm run build
this compiles without error. I created the following test file
const PoweredUP = require("node-poweredup");
const poweredUP = new PoweredUP.PoweredUP();
poweredUP.scan(); // Start scanning for hubs
console.log("Looking for Hubs...");
poweredUP.on("discover", async (hub) => { // Wait to discover hubs
await hub.connect(); // Connect to hub
console.log(`Connected to ${hub.name}!`);
const motorA = await hub.waitForDeviceAtPort("A"); // Make sure a motor is plugged into port A
motorA.rotateByDegrees(20,10).then(function(value) {console.log("test");});
});
and get the expected output:
node-poweredup$ node test.js
Looking for Hubs...
Connected to MyHub2!
test
Connected to MyHub3!
test
When I changed the first line to
const PoweredUP = require(".");
to make it use my self-compiled binary I get
node-poweredup$ node test.js
Looking for Hubs...
Connected to MyHub2!
Connected to MyHub3!
Of course this is only a partial answer because I still don't know why it compiles differently on my machine, but at least I have an idea where to start searching for the problem.
I try to get the ipcRenderer module from electron in typescript to send informations from the current component to the core and to get informations back to the window (electron-chromium-browser).
All I get is a error "Module not found" by transcoding the ts-code to ES5.
const ipc = require('electron').ipcRenderer;`
Update: The Error is switching between the "Module not found" and this one:
ERROR in ./~/electron/index.js
Module build failed: Error: ENOENT, open '/.../node_modules/electron/index.js'
# ./app/components/search/search.ts 12:10-29
That is from the current electron-api. I have also tried to use the import syntax from typescript but the result is the same.
Than I tried to use the electron.ipcRenderer module in a ES5-file, loaded/linked directly in the html-file.
There it worked. Why?
Solved the problem after 10h searching.
Problem was the webpack-transcoder.
https://github.com/chentsulin/webpack-target-electron-renderer
https://github.com/chentsulin/electron-react-boilerplate/blob/master/webpack.config.development.js
Since electron dependency in the browser app is not real, meaning it's not webpacked from node_modules but instead loaded in runtime, the require statement caused errors such as "fs" not found for me.
However you can trick the typescript with this:
if (typeof window['require'] !== "undefined") {
let electron = window['require']("electron");
let ipcRenderer = electron.ipcRenderer;
console.log("ipc renderer", ipcRenderer);
}
Also if you are writing a web app, which only is augmented by electron when it's running inside, this is a better way since you don't have to add electron as a dependency to your webapp just when using the communication parts.
Than I tried to use the electron.ipcRenderer module in a ES5-file, loaded/linked directly in the html-file.
If it works in html but fails in ts it means the error is not in const ipc = require('electron').ipcRenderer;. The error is most likey in the import you have to load your file from html (and not require('electron')).
This solved the problem for me:
You can fix it, just add to the "package.json"
"browser": {
"fs": false,
"path": false,
"os": false }
Source: https://github.com/angular/angular-cli/issues/8272#issuecomment-392777980
You can trick ts with this (dirty hack, but it works):
const { ipcRenderer } = (window as any).require("electron");