I'm running Ubuntu 20.04 under WSL in Windows 11.
Here is my JavaScript file main.mjs:
console.log("In main.mjs");
import { TransferTransaction } from
'./node_modules/#hashgraph/sdk/src/index.js';
console.log("Imported hashgraph");
When I run it using node, it gives the expected result:
> node main.mjs
<pause for a couple of seconds>
In main.mjs
Imported hashgraph
Here is my HTML code page.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<script src='./main.mjs' type="module">
</script>
<p> question </p>
</body>
</html>
When I invoke it:
<In same directory as page.html and main.mjs:>
> python3 -m http.server
<In locator bar:>
localhost:8000/page.html
It gives the error when viewed in the console (F12):
Uncaught TypeError: failed to resolve module specifier "js-logger".
Relative reference must start with either "/", "./", or "../".
There is a js-logger directory in directory node_modules. Here is a listing of the node_modules directory:
#ethersproject
#grpc
#hashgraph
#protobufjs
#types
ansi-regex
ansi-styles
asynckit
axios
base64-js
bignumber.js
bn.js
brorand
buffer
cliui
color-convert
color-name
combined-stream
crypto-es
crypto-js
delayed-stream
elliptic
emoji-regex
escalade
follow-redirects
form-data
get-caller-file
hash.js
hashconnect
hmac-drbg
i
ieee754
inherits
is-fullwidth-code-point
isomorphic-ws
js-base64
js-logger
lodash.camelcase
long
mime-db
mime-types
minimalistic-assert
minimalistic-crypto-utils
multiformats
protobufjs
protocol-buffers-schema
protons
require-directory
signed-varint
simple-crypto-js
string-width
strip-ansi
ts-typed-events
tweetnacl
uint8arrays
utf8
uuid
varint
wrap-ansi
ws
y18n
yargs
yargs-parser
Related
I've been trying to learn the basics of Eel through their documentation. I struggled learning how to trigger a javascript function through python so I tried to download their Hello World example straight from their github. You can open it here.
But I still get the same error, namely: Exception has occurred: AttributeError
module 'eel' has no attribute 'say_hello_js'
The code is as following: (you can also look it up on github in the link abov)
hello.py
import eel
# Set web files folder
eel.init('web')
#eel.expose # Expose this function to Javascript
def say_hello_py(x):
print('Hello from %s' % x)
say_hello_py('Python World!')
eel.say_hello_js('Python World!') # Call a Javascript function
eel.start('hello.html', size=(300, 200)) # Start
web/index.html
<!DOCTYPE html>
<html>
<head>
<title>Hello, World!</title>
<!-- Include eel.js - note this file doesn't exist in the 'web' directory -->
<script type="text/javascript" src="/eel.js"></script>
<script type="text/javascript">
eel.expose(say_hello_js); // Expose this function to Python
function say_hello_js(x) {
console.log("Hello from " + x);
}
say_hello_js("Javascript World!");
eel.say_hello_py("Javascript World!"); // Call a Python function
</script>
</head>
<body>
Hello, World!
</body>
</html>
Could it be that I have a wrong version of python or Eel? I am running Python 3.8.10. I ran pip install eel --upgrade but the issue still occurs.
I cannot pin point the exact issue based on the details you provided. But you can try the following these steps if you're using VSC:
Run this command py -m venv .venv and it will create your virtual environment.
Select the virtual environment's Python interpreter with CTRL + SHIFT + K.
Close out your terminal with the trash icon.
Start the terminal using the virtual environment's Python interpreter with CTRL + J.
Run the command pip install eel.
Create the file hello.py.
Create the directory web.
In web create the file hello.html.
In hello.py use this code:
import eel
eel.init('web')
eel.say_hello_js('Hi from Python')
eel.start('hello.html')
In hello.html use this code:
<!DOCTYPE html>
<html>
<head>
<title>Hello, World!</title>
<!-- Include eel.js - note this file doesn't exist in the 'web' directory -->
<script type="text/javascript" src="/eel.js"></script>
<script type="text/javascript">
eel.expose(say_hello_js); // Expose this function to Python
function say_hello_js(x) {
alert("Hello from " + x);
}
</script>
</head>
<body>
Hello, World!
</body>
</html>
If you followed these steps, you should see the alert box pop up. To trigger a JS function from Python you need to precede the function with the eel expose function like this eel.expose(your_js_function_name);. From Python you would call this function using the eel module and calling that function name like this eel.your_js_function_name(parameter_if_any). Make sure that in your HTML file you have the eel script element in the head. Then another script element after that one with all your functions.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
HTML page I created for my WebAssembly module.
<script>
const importObject = {
env: {
memory:new WebAssembly.Memory({initial:1,maximum:10}),
__memory_base: 0,
__table_base: 0,
}
};
WebAssembly.instantiateStreaming(fetch("x2.wasm"),importObject).then(result => {
const value = result.instance.exports._inc(17);
console.log(value.toString());
});
</script>
</body>
</html>
The cpp file get compiled into wasm without any warnings.
But when the script downloads the wasm module, it does not 'see' the exported functions as functions:
Here's the error shown in the browser console:
Uncaught (in promise) TypeError: result.instance.exports._inc is not a function
What am i missing?
side note- emscripten was included in the source cpp file too.
#include<emscripten>
int inc(int a)
{
return ++a;
}
this is the cpp source file. As you will see i just started learning.
compiler flags:
em++ x2.cpp -s SIDE_MODULE=2 -s EXPORTED_FUNCTIONS=['_inc'] -O1 -o x2.wasm
You may use that method along with ccall for C functions. If you prefer to expose classes in wasm interface you should use Embind for classes
So I've started learning stuff about modules, but I've faced an error right away (probably it's not even about modules) and I've never seen in before.
I use VSCode Live Server for this as well.
My project tree is structured like this:
/modules
- index.html
- scripts.js
- utils.html
The issue is - when I run a function from scripts.js console throws an error:
Uncaught TypeError: Failed to resolve module specifier "prettier". Relative references must start with either "/", "./", or "../".
I don't even have Prettier extension installed. So where does an error comes from?
Here is my index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Modules</title>
<link rel="stylesheet" href="./base.css">
</head>
<body>
<script src="./scripts.js" type="module"></script>
</body>
</html>
scripts.js
import { format } from "prettier";
import { returnHi } from './utils.js';
const name = 'wes';
console.log(returnHi(name));
console.log('working');
And utils.js
export function returnHi(name) {
return `hi ${name}`;
}
So I am trying to learn modules from a youtube video and I'm following along with him but for some reason my code is the exact same as his and is giving me the error
SyntaxError: Cannot use import statement outside a module
I'm not sure if its because my directories are wrong? I have it under
This PC > Desktop > Javascript > module > js > main.js
This is the code from main.js
import{double} from './utils.js'
console.log(double(5))
I also have a index.html file located in the module folder
This is my index.html code.
<!DOCTYPE html>
<head>
<title>JavaScript Modules</title>
<meta name="viewport" content="width=device-width, initial scale=1.0">
<meta charset="utf-8">
<link rel="stylesheet" href="/assets/dcode.css">
<link rel="shortcut icon" href="/assets/favicon.ico" type="image/x-icon">
</head>
<body>
<h1>JavaScript Modules</h1>
<u1>
<li>Split up your code into separate components</li>
<li>Therefore easier to maintain and organize</li>
<li>Supported in major browsers(excl. IE)</li>
</u1>
<script type="module" src="./js/main.js"></script>
</body>
I'm trying to import code from my utils.js file which is in the same folder as main.js
This is my utils.js code.
export function double(n){
return n * 2;
}
When I run the code on the main.js file is where I'm getting the error:
SyntaxError: Cannot use import statement outside a module
You need to run your own webserver. An easy one is to get the Web Server for Chrome. You just run it, point it to your local computer folder, and it will give you a localhost port number where your computer is serving the folder. That way you can access your local folders over HTTP.
With the following folder structure:
/exports/
user.html
importer.js
exporter.js
Where user.html is the page using the importer.js script, which in turn loads exporter.js, you use the following syntax:
user.html
-- the type="module" notation is necessary.
<script src="importer.js" type="module"></script>
importer.js
-- the ./ relative notation is obligatory.
import { doStuff } from './exporter.js'
doStuff()
exporter.js
-- in a production environment, this is your library or module.
function doStuff() {
console.log('Do stuff')
}
export { doStuff }
With a local server, the above setup will log Do stuff in the console.
Forgetting type="module" results in an Uncaught SyntaxError: Cannot use import statement outside a module, not having a relative URL will result in an Uncaught TypeError: Failed to resolve module specifier "exporter.js". Relative references must start with either "/", "./", or "../", and having the wrong URL results in a 404.
I've been generating some tests using NodeJS and Mocha, and I'd like to find a way to place the results into a browser. I know that Mocha has support for this using 'html' reporter and mocha init <dir> however neither seem to be working for me (the reporter actually throws errors without even running a test).
Could someone give me a good example of running a test via Mocha and generating a HTML report?An example I want to mimic is on the visionmedia site. Also, for examples sake we'll say I'm using a test file called example.js.
Thanks in advance for any assistance, it's surprising there are so few example pieces around.
You try to use the html reporter, which throws when you try to use it in Node:
$ mocha --reporter html > report.html
/usr/local/lib/node_modules/mocha/lib/reporters/html.js:194
, div = document.createElement('div')
^
ReferenceError: document is not defined
Per the Mocha documentation (and relevant issue in Github), the htmlreporter only works in the browser, ie. to test client-side code in the browser.
If you want to output HTML for a Node.js test script, use the doc reporter, which will generate HTML.
To get Mocha to run your test in both browser and in the terminal follow this small tutorial:
I'm assuming the following plugins for a normal node.js mocha test suite.
Node.js
Mocha
And the following tree structure:
/root
/test
my_something_spec.js
/javascript
index.html
index.html
Disclaimer: I've blatantly forgone all kinds of best practices but just to point you in the right direction.
<html>
<head>
<meta charset="utf-8">
<title>Mocha Tests</title>
<link rel="stylesheet" href="node_modules/mocha/mocha.css" />
</head>
<body>
<div id="mocha"></div>
<script src="node_modules/mocha/mocha.js"></script>
<script>mocha.setup('bdd')</script>
<script src="test/my_something_spec.js"></script>
<script>
mocha.checkLeaks();
mocha.run();
</script>
</body>
</html>
test/my_something_spec.js
describe("my function", function() {
it("is a function", function() {
expect(true).to.be(true);
});
});
Serving this up with a simple python server python -m SimpleHTTPServer 8080 from the root and visit localhost:8080 will give you a nice and failing test.
And running mocha from the terminal will give you the same output, that expect isn't defined.
I like to test the same code through Node.js and in a browser, depending on the situation. I know you were asking to "place the results into a browser" (from Node.js?), but I hope this will suffice.
This example was created on a windows machine, but it will work on a Mac and Linux also.
You do not require a web-server (Node.js or other) for this to work.
To run the tests in a browser, open up the ./test/index.html file.
To run the tests in command-line, just execute "mocha".
Starting from nothing:
C:\TEMP>mkdir mocha_node_browser
C:\TEMP>cd mocha_node_browser
C:\TEMP\mocha_node_browser>dir
Volume in drive C is MessedUp
Volume Serial Number is CAB2-E609
Directory of C:\TEMP\mocha_node_browser
2014-08-09 12:17 <DIR> .
2014-08-09 12:17 <DIR> ..
0 File(s) 0 bytes
2 Dir(s) 287,218,769,920 bytes free
Initialize the directory that will hold all of your tests. Always call it "test":
C:\TEMP\mocha_node_browser>mocha init test
Edit and/or create some files:
C:\TEMP\mocha_node_browser>gvim -p test_me.js test\index.html test\tests.js
I use Chai. The same chai.js file will be used in both tests.
C:\TEMP\mocha_node_browser>cd test
C:\TEMP\mocha_node_browser\test>curl -O http://chaijs.com/chai.js
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 117k 100 117k 0 0 99902 0 0:00:01 0:00:01 --:--:-- 99902
C:\TEMP\mocha_node_browser\test>cd ..
After creating/editing the files, run the tests via command-line:
C:\TEMP\mocha_node_browser>mocha
.
1 passing (15ms)
...or point your browser at ./test/index.html.
passes: 1
failures: 0
duration: 0.03s
whatever
should return "it worked!"
File contents:
C:\TEMP\mocha_node_browser>type test_me.js
// the function to be tested
function whatever() {
return 'it worked!';
}
// only kicks in when running in Node.js via "mocha"
if (typeof module !== 'undefined') {
module.exports = whatever;
}
Add Chai and your source that you want to test into test/index.html:
C:\TEMP\mocha_node_browser>type test\index.html
<!DOCTYPE html>
<html>
<head>
<title>Mocha</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="mocha.css" />
</head>
<body>
<div id="mocha"></div>
<script src="mocha.js"></script>
<script>mocha.setup('bdd')</script>
<!-- added to index.html: -->
<script src="./chai.js"></script>
<script src="../test_me.js"></script>
<script src="tests.js"></script>
<script>
mocha.run();
</script>
</body>
</html>
Make your tests compatible with command-line and browser
C:\TEMP\mocha_node_browser>type test\tests.js
if (typeof require !== 'undefined') {
// testing in command-line
var chai = require('./chai');
var whatever = require('../test_me');
}
var expect = chai.expect;
describe('whatever', function() {
it('should return "it worked!"', function() {
expect(whatever()).to.equal("it worked!");
});
});