Compiling GMP/MPFR with Emscripten - javascript

Alright, this has been driving me insane. I've been trying this for at least a month, and no where on the internet is helping.
I followed the steps of this. Not even the example works when I do these steps, because when I do it, I get this.
bitcode ==> javascript
warning: unresolved symbol: __gmpz_cmp
warning: unresolved symbol: __gmpz_mul_ui
warning: unresolved symbol: __gmpz_submul_ui
warning: unresolved symbol: __gmpz_init_set_ui
warning: unresolved symbol: __gmpz_mul_2exp
warning: unresolved symbol: __gmpz_init
warning: unresolved symbol: __gmpz_fdiv_qr
warning: unresolved symbol: __gmpz_add
And when I run the resulting complete.js file -
missing function: __gmpz_init
-1
-1
/home/ubuntu/workspace/gmp.js/complete.js:117
throw ex;
^
abort(-1) at Error
at jsStackTrace (/home/ubuntu/workspace/gmp.js/complete.js:1045:13)
at stackTrace (/home/ubuntu/workspace/gmp.js/complete.js:1062:22)
at abort (/home/ubuntu/workspace/gmp.js/complete.js:6743:44)
at ___gmpz_init (/home/ubuntu/workspace/gmp.js/complete.js:1744:56)
at Object._main (/home/ubuntu/workspace/gmp.js/complete.js:4978:2)
at Object.callMain (/home/ubuntu/workspace/gmp.js/complete.js:6627:30)
at doRun (/home/ubuntu/workspace/gmp.js/complete.js:6681:60)
at run (/home/ubuntu/workspace/gmp.js/complete.js:6695:5)
at Object.<anonymous> (/home/ubuntu/workspace/gmp.js/complete.js:6769:1)
at Module._compile (module.js:541:32)
If this abort() is unexpected, build with -s ASSERTIONS=1 which can give more information.

These instructions are for a host running amd64 Debian Buster. It seems that GMP no longer needs 32bit to work with Emscripten (and in any case 32bit Emscripten seems no longer supported?), but I used a chroot for clean environment. After installing, my chroot was 1.6GB large. But I wouldn't recommend using it for compute-intensive code if you can avoid it, in one benchmark my native code was 15 times faster than the same code compiled with Emscripten running in nodejs...
Debian Buster chroot
mkdir emscripten
sudo debootstrap buster emscripten
sudo chroot emscripten /bin/bash
echo "deb http://security.debian.org/debian-security buster/updates main" >> /etc/apt/sources.list
apt update
apt install python cmake g++ git lzip wget nodejs m4
echo "none /dev/shm tmpfs rw,nosuid,nodev,noexec 0 0" >> /etc/fstab
mount /dev/shm
echo "none /proc proc defaults 0 0" >> /etc/fstab
mount /proc
adduser emscripten
su - emscripten
emsdk latest
At time of writing this installed
releases-upstream-b024b71038d1291ed7ec23ecd553bf2c0c8d6da6-64bit
and node-12.9.1-64bit:
git clone https://github.com/juj/emsdk.git
cd emsdk
./emsdk install latest
./emsdk activate latest
source ./emsdk_env.sh
mkdir -p ${HOME}/opt/src
cd ${HOME}/opt/src
gmp 6.1.2
wget https://gmplib.org/download/gmp/gmp-6.1.2.tar.lz
tar xf gmp-6.1.2.tar.lz
cd gmp-6.1.2
emconfigure ./configure --disable-assembly --host none --enable-cxx --prefix=${HOME}/opt
make
make install
cd ..
mpfr 4.0.2
wget https://www.mpfr.org/mpfr-current/mpfr-4.0.2.tar.xz
wget https://www.mpfr.org/mpfr-current/allpatches
tar xf mpfr-4.0.2.tar.xz
cd mpfr-4.0.2
patch -N -Z -p1 < ../allpatches
emconfigure ./configure --host none --prefix=${HOME}/opt --with-gmp=${HOME}/opt
make
make install
cd ..
mpc 1.1.0
wget https://ftp.gnu.org/gnu/mpc/mpc-1.1.0.tar.gz
tar xf mpc-1.1.0.tar.gz
cd mpc-1.1.0
emconfigure ./configure --host none --prefix=${HOME}/opt --with-gmp=${HOME}/opt --with-mpfr=${HOME}/opt
make
make install
cd ..
hello world
Your favourite program using GMP/MPFR/MPC:
emcc -o hello.js hello.c \
${HOME}/opt/lib/libmpc.a ${HOME}/opt/lib/libmpfr.a ${HOME}/opt/lib/libgmp.a
nodejs hello.js

I found out to do it, you need to be using a 32 bit machine. I had a 64 bit machine so I chroot'ed into a 32 bit filesystem using this tutorial.
After that, everything worked well. I was making a Mandelbrot program using GMP and MPFR, and I posted the compiling script (along with the program itself) online on GitHub. Here it is. Adapt it for your own projects.

I packaged it into a NPM library called gmp-wasm. You can find a Dockerized code which builds the library within the source. It exports both low-level functions and an immutable high-level wrapper:
<script src="https://cdn.jsdelivr.net/npm/gmp-wasm"></script>
<script>
gmp.init().then(({
calculate
}) => {
// calculate() automatically deallocates all objects
// created within the callback function
const result = calculate((g) => {
const six = g.Float(1).add(5);
const res = g.Pi().div(six).sin();
return res;
});
document.write(`sin(Pi/6) = ` + result);
});
</script>
Using low-level functions:
<script src="https://cdn.jsdelivr.net/npm/gmp-wasm"></script>
<script>
gmp.init().then(({
calculate, binding
}) => {
const result = calculate((g) => {
const a = g.Float(1);
const b = g.Float(2);
const c = g.Float(0);
// c = a + b
binding.mpfr_add(c.mpfr_t, a.mpfr_t, b.mpfr_t, 0);
return c;
});
document.write(`1 + 2 = ` + result);
});
</script>

Related

/tmp/chromium: error while loading shared libraries: libnss3.so: cannot open shared object file: No such file or directory Vercel

when I try to access my API uploaded on vercel server, I'm getting this error.
Did anyone have the same error?
When I run it locally, it works fine.
2021-02-15T19:38:59.218Z 0109b575-a2e7-478e-aefe-aa3335b5b6b8 ERROR Error: Failed to launch the browser process!
/tmp/chromium: error while loading shared libraries: libnss3.so: cannot open shared object file: No such file or directory
TROUBLESHOOTING: https://github.com/puppeteer/puppeteer/blob/main/docs/troubleshooting.md
at onClose (/var/task/node_modules/puppeteer-core/lib/cjs/puppeteer/node/BrowserRunner.js:193:20)
at Interface. (/var/task/node_modules/puppeteer-core/lib/cjs/puppeteer/node/BrowserRunner.js:183:68)
at Interface.emit (events.js:327:22)
at Interface.close (readline.js:424:8)
at Socket.onend (readline.js:202:10)
at Socket.emit (events.js:327:22)
at endReadableNT (internal/streams/readable.js:1327:12)
at processTicksAndRejections (internal/process/task_queues.js:80:21)
code
import puppeteer, { Page } from 'puppeteer-core'
import chrome from 'chrome-aws-lambda'
export async function getOptions() {
const isDev = !process.env.AWS_REGION
let options;
const chromeExecPaths = {
win32: 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
linux: '/usr/bin/google-chrome',
darwin: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
}
const exePath = chromeExecPaths[process.platform]
if (isDev) {
options = {
args: [],
executablePath: exePath,
headless: true
}
} else {
options = {
args: chrome.args,
executablePath: await chrome.executablePath,
headless: chrome.headless
}
}
return options
}
let _page: Page | null
async function getPage(): Promise<Page> {
if (_page) {
return _page
}
const options = await getOptions()
const browser = await puppeteer.launch(options)
_page = await browser.newPage()
return _page
}
export async function getScreenshot(html: string, { width, height } = { width: 800, height: 800 }) {
const page = await getPage();
await page.setContent(html);
await page.setViewport({ width, height });
const file = await page.screenshot({ type: 'png' });
return file;
}
I had the same issue where puppeteer was running okay on my local environment but when i deployed to AWS EC2 i face up the same error shared loading libraries
Solution
First check the version of nodejs you are running and if its not less than v14.0 or greater than v14.0. Upgrade or downgrade (recommended to upgrade) and restart your app then try.
The most common cause is a bug in Node.js v14.0.0 which broke extract-zip, the module Puppeteer uses to extract browser downloads into the right place. The bug was fixed in Node.js v14.1.0, so please make sure you're running that version or higher. Alternatively, if you cannot upgrade, you could downgrade to Node.js v12, but we recommend upgrading when possible.
Trivial:- Make sure the directory where your project folder is located is not owned by root.
For those who might have experience this issue while running on windows enviroment, You can try to pass ignoreDefaultArgs: ['--disable-extensions'] option when launching it chromium from code i.e
const browser = await puppeteer.launch({ignoreDefaultArgs: ['--disable-extensions']})
This will deactivate default behaviour of puppeteer from disabling any extensions usually used by chromium/chrome.
Linux and MAcOS uses
The issues that results in this error
UnhandledPromiseRejectionWarning: Error: Failed to launch the browser process!
error while loading shared libraries: libnss3.so: cannot open shared object file: No such file or directory TROUBLESHOOTING
is mostly but not all the times caused by missing dependencies that are required in the latest version. The good thing is you can easily check the missing chrome dependencies causing the crash.
Make sure you are in the root folder of your project
Navigate to node_modules folder
Navigate to the folder where puppeteer chrome Linux tools are installed
cd /project_folder/node_modules/puppeteer/.local-chromium/linux-some number/chrome-linux
replace the linux-some number with whatever ls will output
ls at /.local-chromium to check name of your directory
At the last directory [ chrome-linux ] run below command to check the missing dependencies
ldd chrome | grep not
if you see any missing dependencies, run this command to install everything and restart your application.
sudo apt-get install ca-certificates fonts-liberation libappindicator3-1 libasound2 libatk-bridge2.0-0 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgbm1 libgcc1 libglib2.0-0 libgtk-3-0 libnspr4 libnss3 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 lsb-release wget xdg-utils
Voila!! everything should be fixed
Thanks to #andrew-mititi and his awesome answer, I was able to solve the issue in my environment, which is Docker FROM node:16 (which is Debian GNU/Linux 10) + puppeteer v13 (not puppeteer-core). I did the following steps:
build & run Docker container: make build & docker run
go to container: docker exec -it CONTAINER_ID /bin/bash
find pptr chromium folder: ls project_folder/node_modules/puppeteer/.local-chromium, it was linux-961656 in my case
find next folder: ls project_folder/node_modules/puppeteer/.local-chromium/linux-961656, it was chrome-linux
run missing-dependencies script in that folder: ldd node_modules/puppeteer/.local-chromium/linux-961656/chrome-linux/chrome | grep not, it should show something like
libnss3.so => not found
libnssutil3.so => not found
libsmime3.so => not found
libnspr4.so => not found
libatk-1.0.so.0 => not found
libatk-bridge-2.0.so.0 => not found
libcups.so.2 => not found
libdrm.so.2 => not found
libdbus-1.so.3 => not found
libxkbcommon.so.0 => not found
libXcomposite.so.1 => not found
libXdamage.so.1 => not found
libXfixes.so.3 => not found
libXrandr.so.2 => not found
libgbm.so.1 => not found
libasound.so.2 => not found
libatspi.so.0 => not found
The last step was to convert this list into correct apt-get command and add it to the Docker make-script after installing the project's npm dependencies. In my case it was:
RUN apt-get update && apt-get install -y libnss3 libnspr4 libatk1.0-0 libatk-bridge2.0-0 libcups2 libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 libxfixes3 libxrandr2 libgbm1 libasound2
For people who are actually using Vercel and not AWS:
The problem correctly lies in the Node.js version of your app. You must use Node.js 14 instead of 16 like all other answers mentioned. To do this on Vercel, do 2 things:
Go to your project's Settings page, in the General tab, Node.js Version section: Select 14.x
Inside your app's package.json, under engines, set "node": "^14"
// package.json
{
...
"engines": {
"node": "^14"
}
...
}
Reference: Vercel documentation
For anyone having libnss3.so: cannot open shared object file issue on aws lambda. For me the fix was to bump both chrome-aws-lambda and puppeteer-core to version >= 6.0.0 - this is minimum version required while running runtime: nodejs14.x.
Try adding jontewks/puppeteer-heroku-buildpack buildpack. Adding this buildpack worked for me.
heroku buildpacks:add jontewks/puppeteer
Also don't forget to trigger build with a commit.
I didn't notice that my serverless.yml was on runtime: nodejs16.x. When I changed it to nodejs14.x I was able to run without this error on AWS Lambda.
Error
"/tmp/chromium: error while loading shared libraries: libnss3.so: cannot open shared object file: No such file or directory"
Fix
Changed serverless.yml to
provider:
name: aws
runtime: nodejs14.x
and redeployed
I faced this issue while working with linux server, you should install missing dependancies by using below command and restart your nodejs server.
apt-get install ca-certificates fonts-liberation libappindicator3-1 libasound2 libatk-bridge2.0-0 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgbm1 libgcc1 libglib2.0-0 libgtk-3-0 libnspr4 libnss3 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 lsb-release wget xdg-utils

How can I transfer JS to native machine code (using v8)

I've tried the suggest in the url:
How can I see the machine code generated by v8?
Here is what I did:
git clone https://chromium.googlesource.com/chromium/tools/depot_tools
sudo apt-get install libv8-dev
sudo apt-get install g++
sudo apt-get install libgtk2.0-dev
sudo apt-get install g++-multilib
export PATH="$PATH":`pwd`/depot_tools
fetch v8
gclient sync
make ia32.release objectprint=on disassembler=on
v8/out/ia32.release/d8 --print-all-code hello.js > output.txt
(The script is just:print("hello"))
Below are the output:
kind = STUB
major_key = JSEntryStub
compiler = unknown
Instructions (size = 131)
0x35d06040 0 55 push ebp
0x35d06041 1 89e5 mov ebp,esp
0x35d06043 3 6a02 push 0x2
......
0x35d060c2 82 c3 ret
Handler Table (size = 12)
RelocInfo (size = 23)
0x35d06047 external reference (Isolate::context_address) (0xa9533dc)
0x35d06050 external reference (Isolate::c_entry_fp_address) (0xa953410)
......
kind = STUB
major_key = JSEntryStub
compiler = unknown
Instructions (size = 131)
0x35d06120 0 55 push ebb
......
Indeed,I have a batch of code,but it doesn't vary from the input script.
By the way,the output is certainly too much(about 13M text) for a simple script.
Thanks.
With current V8 versions (5.9 or later), you probably want the --print-opt-code flag: initially, V8 generates byte code for its interpreter (which you can inspect with --print-bytecode); once a function is "hot" (i.e. a lot of time is spent executing it), it is sent to the optimizing compiler to generate machine code for it.
Note that you cannot use V8 as a general purpose JavaScript-to-machine-code compiler. The flags mentioned above are intended for debugging; there is no (supported or easy) way to produce working binaries from their output.

Can Emstripten compile the iostream library?

I'm on Ubuntu.
$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 14.04.2 LTS
Release: 14.04
Codename: trusty
I installed Emscripten.
$ sudo apt-get install emscripten
I wrote the following C++ program:
#include <iostream>
int main(){
printf("hello world\n");
}
It compiles as expected.
$ emcc -O1 -s ASM_JS=1 main.cpp
$
However, when I write a similar program using the iostream facilities:
#include <iostream>
int main(){
std::cout << "hello world" << std::endl;
}
It fails to build.
$ emcc -O1 -s ASM_JS=1 main.cpp
aborting from js compiler due to exception: unknown vector type <4 x i8> | undefined
aborting from js compiler due to exception: unknown vector type <4 x i8> | undefined
aborting from js compiler due to exception: unknown vector type <4 x i8> | undefined
Traceback (most recent call last):
File "/usr/share/emscripten/emscripten.py", line 1352, in <module>
_main(environ=os.environ)
File "/usr/share/emscripten/emscripten.py", line 1340, in _main
temp_files.run_and_clean(lambda: main(
File "/usr/share/emscripten/tools/tempfiles.py", line 39, in run_and_clean
return func()
File "/usr/share/emscripten/emscripten.py", line 1348, in <lambda>
DEBUG_CACHE=DEBUG_CACHE,
File "/usr/share/emscripten/emscripten.py", line 1235, in main
jcache=jcache, temp_files=temp_files, DEBUG=DEBUG, DEBUG_CACHE=DEBUG_CACHE)
File "/usr/share/emscripten/emscripten.py", line 292, in emscript
assert len(output) == 2, 'Did not receive forwarded data in an output - process failed? We only got: ' + output[0][-3000:]
AssertionError: Did not receive forwarded data in an output - process failed? We only got: ((HEAP32[(($1)>>2)])|0);
$3=((($2)-(12))|0);
$4=$3;
$5=((HEAP32[(($4)>>2)])|0);
$6=$this;
$_sum=((($5)+(24))|0);
$7=(($6+$_sum)|0);
$8=$7;
$9=((HEAP32[(($8)>>2)])|0);
$10=($9|0)==0;
if ($10) {
STACKTOP=sp;return (($this)|0);
}
$12=(($__s)|0);
HEAP8[($12)]=0;
$13=(($__s+4)|0);
HEAP32[(($13)>>2)]=$this;
$_sum_i=((($5)+(16))|0);
$14=(($6+$_sum_i)|0);
$15=$14;
$16=((HEAP32[(($15)>>2)])|0);
$17=($16|0)==0;
do {
if ($17) {
$_sum1_i=((($5)+(72))|0);
$19=(($6+$_sum1_i)|0);
$20=$19;
$21=((HEAP32[(($20)>>2)])|0);
$22=($21|0)==0;
if (!($22)) {
$24=((__ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEE5flushEv($21))|0);
}
HEAP8[($12)]=1;
$26=((HEAP32[(($1)>>2)])|0);
$27=((($26)-(12))|0);
$28=$27;
$29=((HEAP32[(($28)>>2)])|0);
$_sum1=((($29)+(24))|0);
$30=(($6+$_sum1)|0);
$31=$30;
$32=((HEAP32[(($31)>>2)])|0);
$33=$32;
$34=$32;
$35=((HEAP32[(($34)>>2)])|0);
$36=(($35+24)|0);
$37=((HEAP32[(($36)>>2)])|0);
$38=((FUNCTION_TABLE_ii[($37)&{{{ FTM_ii }}}]($33))|0);
$39=($38|0)==-1;
if (!($39)) {
break;
}
$41=((HEAP32[(($1)>>2)])|0);
$42=((($41)-(12))|0);
$43=$42;
$44=((HEAP32[(($43)>>2)])|0);
$45=(($6+$44)|0);
$46=$45;
$_sum2=((($44)+(16))|0);
$47=(($6+$_sum2)|0);
$48=$47;
$49=((HEAP32[(($48)>>2)])|0);
$50=$49|1;
__ZNSt3__18ios_base5clearEj($46,$50);
}
} while(0);
__ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEE6sentryD2Ev($__s);
STACKTOP=sp;return (($this)|0);
}
function __ZNSt3__18ios_base33__set_badbit_and_consider_rethrowEv($this){
$this=($this)|0;
var $1=0,$2=0,$3=0,$4=0,$5=0,$6=0,$7=0,label=0;
$1=(($this+16)|0);
$2=((HEAP32[(($1)>>2)])|0);
$3=$2|1;
HEAP32[(($1)>>2)]=$3;
$4=(($this+20)|0);
$5=((HEAP32[(($4)>>2)])|0);
$6=$5&1;
$7=($6|0)==0;
if ($7) {
return;
} else {
___cxa_rethrow();
}
}
function __ZNSt3__113basic_istreamIwNS_11char_traitsIwEEED0Ev($this){
$this=($this)|0;
var $1=0,$2=0,label=0;
$1=(($this+8)|0);
__ZNSt3__18ios_baseD2Ev($1);
$2=$this;
__ZdlPv($2);
return;
}
function __ZNSt3__113basic_istreamIwNS_11char_traitsIwEEED1Ev($this){
$this=($this)|0;
var $1=0,label=0;
$1=(($this+8)|0);
__ZNSt3__18ios_baseD2Ev($1);
return;
}
function __ZTv0_n12_NSt3__113basic_istreamIwNS_11char_traitsIwEEED0Ev($this){
$this=($this)|0;
var $1=0,$2=0,$3=0,$4=0,$5=0,$6=0,$7=0,$_sum=0,$8=0,$9=0,label=0;
$1=$this;
$2=$this;
$3=((HEAP32[(($2)>>2)])|0);
$4=((($3)-(12))|0);
$5=$4;
$6=((HEAP32[(($5)>>2)])|0);
$7=(($1+$6)|0);
$_sum=((($6)+(8))|0);
$8=(($1+$_sum)|0);
$9=$8;
__ZNSt3__18ios_baseD2Ev($9);
__ZdlPv($7);
return;
}
function __ZTv0_n12_NSt3__113basic_istreamIwNS_11char_traitsIwEEED1Ev($this){
$this=($this)|0;
var $1=0,$2=0,$3=0,$4=0,$5=0,$6=0,$_sum=0,$7=0,$8=0,label=0;
$1=$this;
$2=$this;
$3=((HEAP32[(($2)>>2)])|0);
$4=((($3)-(12))|0);
$5=$4;
$6=((HEAP32[(($5)>>2)])|0);
$_sum=((($6)+(8))|0);
$7=(($1+$_sum)|0);
$8=$7;
__ZNSt3__18ios_baseD2Ev($8);
return;
}
Traceback (most recent call last):
File "/usr/bin/emcc", line 1864, in <module>
final = shared.Building.emscripten(final, append_ext=False, extra_args=extra_args)
File "/usr/share/emscripten/tools/shared.py", line 1276, in emscripten
assert os.path.exists(filename + '.o.js') and len(open(filename + '.o.js', 'r').read()) > 0, 'Emscripten failed to generate .js: ' + str(compiler_output)
AssertionError: Emscripten failed to generate .js:
I was under the impression that Emscripten has come a long way, and is capable of compiling entire C++ games for the browser! Is there some kind of flag or configuration I missed in order to sucessfully compile portions of the C++ standard library? I know that clang/gcc compilers will link against the C++ standard shared library by default. Does the issue have something to do with that you think?
I have also tried using the command em++ in place of emcc and recieved the same error message.
If relevant, here is the default configuration that was built when running emscripten for the first time:
$ cat ~/.emscripten
# Note: If you put paths relative to the home directory, do not forget os.path.expanduser
import os
# this helps projects using emscripten find it
EMSCRIPTEN_ROOT = os.path.expanduser(os.getenv('EMSCRIPTEN') or '/usr/share/emscripten') # directory
LLVM_ROOT = os.path.expanduser(os.getenv('LLVM') or '/usr/bin') # directory
PYTHON = os.path.expanduser(os.getenv('PYTHON') or '/usr/bin/python2') # executable
# See below for notes on which JS engine(s) you need
NODE_JS = os.path.expanduser(os.getenv('NODE') or '/usr/bin/node') # executable
SPIDERMONKEY_ENGINE = [os.path.expanduser(os.getenv('SPIDERMONKEY') or 'js')] # executable
V8_ENGINE = os.path.expanduser(os.getenv('V8') or 'd8') # executable
JAVA = 'java' # executable
TEMP_DIR = '/tmp'
CRUNCH = os.path.expanduser(os.getenv('CRUNCH') or 'crunch') # executable
#CLOSURE_COMPILER = '..' # define this to not use the bundled version
########################################################################################################
# Pick the JS engine to use for running the compiler. This engine must exist, or
# nothing can be compiled.
#
# Recommendation: If you already have node installed, use that. Otherwise, build v8 or
# spidermonkey from source. Any of these three is fine, as long as it's
# a recent version (especially for v8 and spidermonkey).
COMPILER_ENGINE = NODE_JS
#COMPILER_ENGINE = V8_ENGINE
#COMPILER_ENGINE = SPIDERMONKEY_ENGINE
# All JS engines to use when running the automatic tests. Not all the engines in this list
# must exist (if they don't, they will be skipped in the test runner).
#
# Recommendation: If you already have node installed, use that. If you can, also build
# spidermonkey from source as well to get more test coverage (node can't
# run all the tests due to node issue 1669). v8 is currently not recommended
# here because of v8 issue 1822.
JS_ENGINES = [NODE_JS] # add this if you have spidermonkey installed too, SPIDERMONKEY_ENGINE]
I can't seem to find a way to get the basic C++ program above to successfully compile.
First, your program compiles fine for me with emcc. Your original program (with printf) causes emcc to assume it is compiling C code and as such it will auto-include stdio.h as C does. Your second program is having more trouble, probably due to an install error (for me I had an issue like this because my version of LLVM doesn't line up with the exact version Emscripten needed.)
Unfortunately, my understanding is that this is a common problem with emscripten and auto installers like apt-get -- I had the problem with both port and brew on my Mac.
The solution is to get Emscripten through the SDK, which bundles all of the sensitive pieces together: https://kripken.github.io/emscripten-site/docs/getting_started/downloads.html
Follow the instructions there carefully. The two problems I ran into were that it expects Python 2 to be called python2 on your system and the script to adjust your default path assumes you're using bash (if you are, it should work fine.)

Error Compiling node.js v0.10.31 for armv7

When trying to compile Node.js v0.10.31 (and v0.10.30) on Ubuntu 14.04 for use on Raspberry pi (running ARM). I'm using the following compiler flags:
export AR=arm-linux-gnueabihf-ar
export CC=arm-linux-gnueabihf-gcc
export CXX=arm-linux-gnueabihf-g++
export LINK=arm-linux-gnueabihf-g++
However I get the following error:
make -C out BUILDTYPE=Release V=1
make[1]: Entering directory `/home/ubuntu/node/out'
arm-linux-gnueabihf-g++ -pthread -rdynamic -Wl,--whole-archive /home/ubuntu/node/out/Release/libopenssl.a -Wl,--no-whole-archive -Wl,--whole-archive /home/ubuntu/node/out/Release/obj.target/deps/v8/tools/gyp/libv8_base.a -Wl,--no-whole-archive -pthread -o /home/ubuntu/node/out/Release/node -Wl,--start-group /home/ubuntu/node/out/Release/obj.target/node/src/fs_event_wrap.o /home/ubuntu/node/out/Release/obj.target/node/src/cares_wrap.o /home/ubuntu/node/out/Release/obj.target/node/src/handle_wrap.o /home/ubuntu/node/out/Release/obj.target/node/src/node.o /home/ubuntu/node/out/Release/obj.target/node/src/node_buffer.o /home/ubuntu/node/out/Release/obj.target/node/src/node_constants.o /home/ubuntu/node/out/Release/obj.target/node/src/node_extensions.o /home/ubuntu/node/out/Release/obj.target/node/src/node_file.o /home/ubuntu/node/out/Release/obj.target/node/src/node_http_parser.o /home/ubuntu/node/out/Release/obj.target/node/src/node_javascript.o /home/ubuntu/node/out/Release/obj.target/node/src/node_main.o /home/ubuntu/node/out/Release/obj.target/node/src/node_os.o /home/ubuntu/node/out/Release/obj.target/node/src/node_script.o /home/ubuntu/node/out/Release/obj.target/node/src/node_stat_watcher.o /home/ubuntu/node/out/Release/obj.target/node/src/node_string.o /home/ubuntu/node/out/Release/obj.target/node/src/node_zlib.o /home/ubuntu/node/out/Release/obj.target/node/src/pipe_wrap.o /home/ubuntu/node/out/Release/obj.target/node/src/signal_wrap.o /home/ubuntu/node/out/Release/obj.target/node/src/string_bytes.o /home/ubuntu/node/out/Release/obj.target/node/src/stream_wrap.o /home/ubuntu/node/out/Release/obj.target/node/src/slab_allocator.o /home/ubuntu/node/out/Release/obj.target/node/src/tcp_wrap.o /home/ubuntu/node/out/Release/obj.target/node/src/timer_wrap.o /home/ubuntu/node/out/Release/obj.target/node/src/tty_wrap.o /home/ubuntu/node/out/Release/obj.target/node/src/process_wrap.o /home/ubuntu/node/out/Release/obj.target/node/src/v8_typed_array.o /home/ubuntu/node/out/Release/obj.target/node/src/udp_wrap.o /home/ubuntu/node/out/Release/obj.target/node/src/node_crypto.o /home/ubuntu/node/out/Release/obj.target/deps/openssl/libopenssl.a /home/ubuntu/node/out/Release/obj.target/deps/zlib/libchrome_zlib.a /home/ubuntu/node/out/Release/obj.target/deps/http_parser/libhttp_parser.a /home/ubuntu/node/out/Release/obj.target/deps/cares/libcares.a /home/ubuntu/node/out/Release/obj.target/deps/uv/libuv.a /home/ubuntu/node/out/Release/obj.target/deps/v8/tools/gyp/libv8_base.a /home/ubuntu/node/out/Release/obj.target/deps/v8/tools/gyp/libv8_nosnapshot.a -Wl,--end-group -lm -ldl -lrt
/home/ubuntu/node/out/Release/libopenssl.a(armcap.o): In function `OPENSSL_cpuid_setup':
armcap.c:(.text.startup+0x0): multiple definition of `OPENSSL_cpuid_setup'
/home/ubuntu/node/out/Release/libopenssl.a(cryptlib.o):cryptlib.c:(.text+0x360): first defined here
/home/ubuntu/node/out/Release/libopenssl.a(armcap.o): In function `OPENSSL_rdtsc':
armcap.c:(.text+0x36): undefined reference to `_armv7_tick'
/home/ubuntu/node/out/Release/libopenssl.a(armcap.o): In function `OPENSSL_cpuid_setup':
armcap.c:(.text.startup+0xe0): undefined reference to `_armv7_tick'
armcap.c:(.text.startup+0x10c): undefined reference to `_armv7_neon_probe'
collect2: error: ld returned 1 exit status
make[1]: *** [/home/ubuntu/node/out/Release/node] Error 1
make[1]: Leaving directory `/home/ubuntu/node/out'
make: *** [node] Error 2
Any ideas how to solve this error? Thank you!
I recently installed Node on a Raspberry Pi (do not use apt-get, even on Raspbian. If you can move to Raspbian, as far as I know Ubuntu doesn't like ARM). Try this:
$ cd /home/pi/node/ #or any directory you want
$ wget http://node-arm.herokuapp.com/node_latest_armhf.deb
$ sudo dpkg -i node_latest_armhf.deb
If you try to open the REPL ($ node) and this gives you an error, it's probably because it can't find the executable find. In that case this following command made it work for me:
$ hash -r
I used the following to install node.js on RPi.
Install Node on the Raspberry Pi in 5 minutes
The problem I found was that the latest node.js distribution (v0.10.31) did not include the precompiled version for the RPi. I had to go the last distribution that contained the precompiled node.js for the RPi (v0.10.28). Here is the link to the distribution repository:
http://nodejs.org/dist/

ReferenceError: TextEncoder is not defined

I'm writing a simple addon in Firefox - 24, on Linux.
I get the error:
ReferenceError: TextEncoder is not defined
when I do: var encoder = new TextEncoder();
the function I'm using is:
function write_text(filename, text) {
var encoder = new TextEncoder();
var data = encoder.encode(text);
Task.spawn(function() {
let pfh = OS.File.open("/tmp/foo", {append: true});
yield pfh.write(text);
yield pfh.flush();
yield pfh.close();
});
}
if you are having this error while running node server
locate this file node_modules/whatwg-url/dist/encoding.js or .../lib/encoding.js
add this line at top const { TextEncoder, TextDecoder } = require("util");
In nodejs you can solve with util:
var util= require('util');
var encoder = new util.TextEncoder('utf-8');
If you experienced this because of using Mongodb via npm install mongodb then the simplest way is just to upgrade your Node Version. Needs to be higher than version 12; I used version 16 and it clearly fixed my problem
This issue occurs in node 10 or lower version only. To resolve this issue upgrade node version to 12 or higher and then rm -rf node_modules && npm i
Or If you don't want to upgrade node version, then,
Locate this file
node_modules/whatwg-url/dist/encoding.js // If dist folder
node_modules/whatwg-url/lib/encoding.js // If lib folder
And add this line in encoding.js file
const { TextEncoder, TextDecoder } = require("./utils"); // if utils file
const { TextEncoder, TextDecoder } = require("./util"); // if util file
Ah, you're using the SDK, I gather when re-reading the actual error of your other question.
You need to import TextEncoder explicitly from some other module, as SDK modules lack the class.
You need to yield OS.File.open.
append: is only supported in Firefox 27+
.flush() is only supported in Firefox 27+ (and a bad idea anyway). Use .writeAtomic if you need that.
You write: true to write to a file.
Here is a full, working example I tested in Firefox 25 (main.js)
const {Cu} = require("chrome");
// It is important to load TextEncoder like this using Cu.import()
// You cannot load it by just |Cu.import("resource://gre/modules/osfile.jsm");|
const {TextEncoder, OS} = Cu.import("resource://gre/modules/osfile.jsm", {});
const {Task} = Cu.import("resource://gre/modules/Task.jsm", {});
function write_text(filename, text) {
var encoder = new TextEncoder();
var data = encoder.encode(text);
filename = OS.Path.join(OS.Constants.Path.tmpDir, filename);
Task.spawn(function() {
let file = yield OS.File.open(filename, {write: true});
yield file.write(data);
yield file.close();
console.log("written to", filename);
}).then(null, function(e) console.error(e));
}
write_text("foo", "some text");
I was also getting this error so I solved it in this way,
in nodejs project go to the node_modules/whatwg-url/dist/encoding.js file in that add this line =>
const {TextDecoder, TextEncoder} = require("util");
And your problem is solved
A text encoder for Node.js can be found in the util module. You can access it like so:
const util = require('util');
const TextEncoder = new util.TextEncoder();
One of the roles of the TextEncoder is to convert a string of text into an array of bytes. You can achieve this like so:
const data = TextEncoder.encode(
JSON.stringify({ c: "Green" })
);
// Uint8Array [ 123, 34, 99, 34, 58, 34, 71, 114, 101, 101, 110, 34, 125 ]
The array returned is called a Uint8Array. It consists of integers in the range 0 to 255.
Note that TextEncoder only supports UTF-8 encoding.
For me upgrade Node.js version resolved this issue
Open your encoding.js folder in node_modules>whatwg-url>dist
And in place of:
"use strict";
const utf8Encoder = new TextEncoder();
const utf8Decoder = new TextDecoder("utf-8", { ignoreBOM: true });
Write this code:
"use strict";
var util= require('util');
const utf8Encoder = new util.TextEncoder();
const utf8Decoder = new util.TextDecoder("utf-8", { ignoreBOM: true });
all you where missing is this small part by including utils.
The TextEncoder can be found in the sdk/io/buffer module:
let { TextEncoder, TextDecoder } = require('sdk/io/buffer')
If it's an error in node_modules/whatwg_url/dist/encoding.js folder then uninstall MongoDB by
npm uninstall mongodb
and reinstall it
npm install --save mongodb
I was also facing the same problem in my project but I fixed this issue by upgrading my node version from 10 to 12. May be this issue now a days can occurred due to lower version of node we are using in our project.
This looks like a node version error because I solved it by updating from 10 to 16 and after that, I installed dependencies and open a new terminal.
Update node to 14 or higher, I used Node Version Manager (NVM)
Delete node_modules directory, on linux:
rm -rf node_modules
Install dependencies with npm install
Close and open a new terminal
Run app with node or nodemon
Done!
This might help others.
I was getting the same error and I almost tried all the above solutions, but nothing works for me. Finally, I update the npm version and everything is fine.
When I installed the Next App the npm version was 6.14.4.
I update the version and all errors are fixed you don't need to change anything in the core files just update the version in my case recommended 8.11.0.
npm -v // Check the version
npm install -g npm#latest // Get the latest version
OR
npm install -g npm#8.11.0 // Get the Spacific version
Complete guid here
delete your 'node_modules' folder
rm -rf node_modules
then re-install dependencies
npm i
If you are using 'mongoose' greater than v6 you need at least Node.js v12
I was facing the same error, because of having to install old nodejs. This problem can be solved by installing the latest nodejs.
To update nodejs to nodejs to 14.x
sudo apt update
curl -sL https://deb.nodesource.com/setup_14.x | sudo bash -
sudo apt install -y nodejs
node -v
It's a node version problem.
Described by #yhojann-cl here
I have the same problem:
In /usr/bin/node I have 10.x, but 16.x is installed by nvm.
In my case, I had multiple node versions installed, and current project required a more recent node version. To fix the problem I did the following steps.
To check the current version of node running, in the terminal use the command
node --version
Output in the Terminal :
The following command will list the different node versions already installed in your system.
nvm ls
Output in the Terminal :
To switch to more recent version of the node ie, v16.17.0, use the following command in the terminal
nvm use v16.17.0
Output in the Terminal :
Now confirm the current version of the node by
node --version
Output in Terminal:
I encountered this when running automated tests with jest and rendering a component that included import { AgGridColumn, AgGridReact } from "ag-grid-react".
The solution is to mock out that function as follows:
jest.mock('ag-grid-react', () => ({
__esModule: true,
AgGridReact: jest.fn((x) => <div>{x.children}</div>),
AgGridColumn: jest.fn(() => <div />),
}));
I was getitng the same error after adding the mongodb, i resolve it by upgrading to node version
nvm use 16.16.0
TextEncoder is native function in javascript, check the version that suit the ability.
https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder#browser_compatibility
Chrome version >=38, Edge version >=79, Firefox version >=18, Node verison >=11.0.0...

Categories

Resources