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
I have a webpack-dev-server running that compiles and serves some Babel/React code. I have gotten as far as to have it serve the compiled client.js over localhost:3001.
But when I try to include the script in my HTML, I get the following error in Chrome's developer console:
routerWarning.js:19 Uncaught SyntaxError: Unexpected token :
That line belongs to react-router and contains the following code:
process.env.NODE_ENV !== 'production' ? _warning2['default'].apply(undefined, [falseToWarn, message].concat(args)) : undefined;
First, I don't see how that line of code would cause a syntax error. And second, I don't understand how it got in, because this looks like a piece of compiled (babelified) code to me. And finally, I don't know how to fix it! :(
Any help would be greatly appreciated.
I was using webpack's DefinePlugin to set process.env.BABEL_ENV like this:
new DefinePlugin({
'process.env': {
BABEL_ENV: JSON.stringify('client')
}
});
This resulted in webpack replacing all instances of process.env in the code with {"BABEL_ENV":"client"}. The SyntaxError was caused in this part, not in the ternary expression.
I fixed it by setting process.env.BABEL_ENV like this:
new DefinePlugin({
'process.env.BABEL_ENV': JSON.stringify('client')
});
I want Node.js to read form.html when the domain name is localhost:3000/form, but for some reason, it always gives me an error 500 page.
The content parameter in the callback function of fs.readFile gets undefined, even though the path of the file is correct.
app.get('/form', function(req, res){
fs.readFile('/form.html', function(error, content){
if(error){
// This get's always executed... I don't know why.
// content = undefined.
res.writeHead(500);
res.end();
}
else{
res.writeHead(200, { 'content-type' : 'text/html' });
processFile(content);
res.end(content, 'utf-8');
}
});
});
added error message:
{ [Error: ENOENT, open 'C:\form.html'] errno: 34, code: 'ENOENT',
path: 'C:\form.html' }
Do I have to specify the full path to the file...?
After I removed the / I get this path:
C:\Users\deno_000\form.html
My files are all in the same directory, and on the left side of my editor you can see it:
http://i59.tinypic.com/2eqdp2o.jpg
/ in most file systems = root directory.
Either remove the / or add a dot infront like form.html or ./form.html.
. is the current directory
.. is the parent directory
./form.html = [current directory]/form.html]
The error is similar to file not found.
The html file would need to be in the same folder as the .js node file for this to work. If you have it in another path, use that path. \
Note you can also use:
Path#
Stability: 3 - Stable
This module contains utilities for handling and transforming file paths. Almost all these methods perform only string transformations. The file system is not consulted to check whether paths are valid.
Use require('path') to use this module.
http://nodejs.org/api/path.html
Had the same problem. Using __dirname fixed it.
Let's suppose I can access the following code:
http://localhost/web/src/js/myApp.js
Now I want to load myApp.js using requirejs from the javascript command line mode.
I did try the following but it does not work. Any ideas?
requirejs.config({
baseUrl: "http://localhost/web/src/"
});
require("js/myApp"); // Error: Module name 'js/myApp' has not been loaded yet for context: _ http://requirejs.org/docs/errors.html#notloaded
That's because require('FILENAME') is used for loading already loaded files...i don't know what's the purpose behind it. You should use:
require(['module'], function(mod) {
... do some work ...
// later, maybe if you want this (although, i don't understand why)
require('module', function(m) {
... do some work with m - the new (or old?) module!
})
});
I'm using requireJS to load scripts. It has this detail in the docs:
The path that is used for a module name should not include the .js
extension, since the path mapping could be for a directory.
In my app, I map all of my script files in a config path, because they're dynamically generated at runtime (my scripts start life as things like order.js but become things like order.min.b25a571965d02d9c54871b7636ca1c5e.js (this is a hash of the file contents, for cachebusting purposes).
In some cases, require will add a second .js extension to the end of these paths. Although I generate the dynamic paths on the server side and then populate the config path, I have to then write some extra javascript code to remove the .js extension from the problematic files.
Reading the requireJS docs, I really don't understand why you'd ever want the path mapping to be used for a directory. Does this mean it's possible to somehow load an entire directory's worth of files in one call? I don't get it.
Does anybody know if it's possible to just force require to stop adding .js to file paths so I don't have to hack around it?
thanks.
UPDATE: added some code samples as requested.
This is inside my HTML file (it's a Scala project so we can't write these variables directly into a .js file):
foo.js.modules = {
order : '#Static("javascripts/order.min.js")',
reqwest : 'http://5.foo.appspot.com/js/libs/reqwest',
bean : 'http://4.foo.appspot.com/js/libs/bean.min',
detect : 'order!http://4.foo.appspot.com/js/detect/detect.js',
images : 'order!http://4.foo.appspot.com/js/detect/images.js',
basicTemplate : '#Static("javascripts/libs/basicTemplate.min.js")',
trailExpander : '#Static("javascripts/libs/trailExpander.min.js")',
fetchDiscussion : '#Static("javascripts/libs/fetchDiscussion.min.js")'
mostPopular : '#Static("javascripts/libs/mostPopular.min.js")'
};
Then inside my main.js:
requirejs.config({
paths: foo.js.modules
});
require([foo.js.modules.detect, foo.js.modules.images, "bean"],
function(detect, images, bean) {
// do stuff
});
In the example above, I have to use the string "bean" (which refers to the require path) rather than my direct object (like the others use foo.js.modules.bar) otherwise I get the extra .js appended.
Hope this makes sense.
If you don't feel like adding a dependency on noext, you can also just append a dummy query string to the path to prevent the .js extension from being appended, as in:
require.config({
paths: {
'signalr-hubs': '/signalr/hubs?noext'
}
});
This is what the noext plugin does.
requirejs' noext plugin:
Load scripts without appending ".js" extension, useful for dynamic scripts...
Documentation
check the examples folder. All the info you probably need will be inside comments or on the example code itself.
Basic usage
Put the plugins inside the baseUrl folder (usually same folder as the main.js file) or create an alias to the plugin location:
require.config({
paths : {
//create alias to plugins (not needed if plugins are on the baseUrl)
async: 'lib/require/async',
font: 'lib/require/font',
goog: 'lib/require/goog',
image: 'lib/require/image',
json: 'lib/require/json',
noext: 'lib/require/noext',
mdown: 'lib/require/mdown',
propertyParser : 'lib/require/propertyParser',
markdownConverter : 'lib/Markdown.Converter'
}
});
//use plugins as if they were at baseUrl
define([
'image!awsum.jpg',
'json!data/foo.json',
'noext!js/bar.php',
'mdown!data/lorem_ipsum.md',
'async!http://maps.google.com/maps/api/js?sensor=false',
'goog!visualization,1,packages:[corechart,geochart]',
'goog!search,1',
'font!google,families:[Tangerine,Cantarell]'
], function(awsum, foo, bar, loremIpsum){
//all dependencies are loaded (including gmaps and other google apis)
}
);
I am using requirejs server side with node.js. The noext plugin does not work for me. I suspect this is because it tries to add ?noext to a url and we have filenames instead of urls serverside.
I need to name my files .njs or .model to separate them from static .js files. Hopefully the author will update requirejs to not force automatic .js file extension conventions on the users.
Meanwhile here is a quick patch to disable this behavior.
To apply this patch (against version 2.1.15 of node_modules/requirejs/bin/r.js) :
Save in a file called disableAutoExt.diff or whatever and open a terminal
cd path/to/node_modules/
patch -p1 < path/to/disableAutoExt.diff
add disableAutoExt: true, to your requirejs.config: requirejs.config({disableAutoExt: true,});
Now we can do require(["test/index.njs", ...] ... and get back to work.
Save this patch in disableAutoExt.diff :
--- mod/node_modules/requirejs/bin/r.js 2014-09-07 20:54:07.000000000 -0400
+++ node_modules/requirejs/bin/r.js 2014-12-11 09:33:21.000000000 -0500
## -1884,6 +1884,10 ##
//Delegates to req.load. Broken out as a separate function to
//allow overriding in the optimizer.
load: function (id, url) {
+ if (config.disableAutoExt && url.match(/\..*\.js$/)) {
+ url = url.replace(/\.js$/, '');
+ }
+
req.load(context, id, url);
},
The patch simply adds the following around line 1887 to node_modules/requirejs/bin/r.js:
if (config.disableAutoExt && url.match(/\..*\.js$/)) {
url = url.replace(/\.js$/, '');
}
UPDATE: Improved patch by moving url change deeper in the code so it no longer causes a hang after calling undef on a module. Needed undef because:
To disable caching of modules when developing with node.js add this to your main app file:
requirejs.onResourceLoad = function(context, map)
{
requirejs.undef(map.name);
};