Can I deploy the same WASM javascript modules to node-chakracore as I can to nodejs v8?
ChakraCore has supported WebAssembly since v1.4, and node-chakracore has supported it via JavaScript since 8.x:
WASM is supported in Node-ChakraCore if you're using the WebAssembly
methods from JavaScript. Using basic.wasm from here, the following
code worked with Node-ChakraCore:
const fs = require('fs'); const buf = fs.readFileSync('basic.wasm')
async function test() {
try {
const module = await WebAssembly.compile(buf);
const inst = new WebAssembly.Instance(module, {test: {foo: function(a){console.log(`foo called: ${a}`); return 2;}}});
console.log(inst.exports.a(1));
} catch (reason) {
console.log(`Failed: ${reason}`)
} }
test();
https://github.com/sass/node-sass/pull/1777#discussion_r127280773
Alternatively, you can use node-wasm to load your wasm file and then in your node js app, do this:
import loadWasm from 'node-wasm';
async function run() {
const {rust_function} = await loadWasm('/local/path/to/wasm');
const result = rust_function();
console.log(result);
}
run();
There's a complete example here in the same repo. Good luck!
Related
Is there any possible way to use require() instead of import in wdio latest?
facing issues when upgraded to latest webdriverIO.
You can use below if it is a page object you are trying to import
//somePage.js
var somePage = function(){
this.eleClick = async function(){
//some code
}
}
module.export = new somePage();
//test.js
const page = require("somePage.js");
async function test(){
page.eleClick();
}
I need to pass a function that is written in typescript which should run in the browser. The issue that I am having is that either I need to have the module I am testing transpiled and them encoded so I can pass it to the browser in puppeteer and it will run normally. This was the approach I was using, and it works. in short I was using es-build to bundle the module. and using readFile then encoding so I can, in the browser import it and run it there.
I am thinking if there is a better way to do this with jest-puppeteer? I can't use page.exposeFunction() because that is running on node environment. and passing the encoded function will give the browser ts code which is not what I want. To understand better look at the code bellow.
//file: module_under-test.e2e.test.ts
//importing does not help us because we might need the whole module encoded
import { testFn } from './module_under-test';
import fs, { readFileSync } from 'fs';
import util from 'util';
const readFile = util.promisify(fs.readFile);
//this will encode the module in a string, so it can be imported in the browser.
async function importer(path) {
return `data:text/javascript;utf-8,${encodeURIComponent((await readFile(path, { encoding: 'utf-8' })))}`;
}
describe('Basic authentication e2e tests', () => {
beforeAll(async () => {
await page.setViewport( {
width: 1920,
height: 1080,
deviceScaleFactor: 1
} );
//we do stuff like opening the page and logging in, etc
});
it('testToRunOnBrowser', async () => {
//module should be already transpiled but this was the old approach. I would use importer from the dist folder.
//with this the test pass but we don't want to have to transpile code everytime to run it.
//since we could already do it with only esbuild and puppeteer
expect(await page.evaluate(testToRunOnBrowser,await importer('../dist/module_under-test.mjs'))).toBe(true);
})
});
export async function testToRunOnBrowser(deps) {
const {testFn} = await import(deps)
const ctx = new browserGlobalFunctionCtx();
const data = ctx.DoGLobalBrowserThings();
ctx.load(data);
const dataLoaded = await testFn()
return dataLoaded === 'what I want to assert'
}
One way I did think but I was not able to do, is servng the whole src folder since the code from this project should all be tested on the browser. With that I can use babel standalone with "#babel/plugin-transform-modules-umd" and just import ts on the browser. any ideas or pointers how to do that with jest-puppeteer?
How can i get the user docs folder path for an electron app running on the desktop.
I've tried the following but get an error that app is undefined.
import fs from "fs";
const { app } = require("electron");
export function getFilepath() {
const filepath = app.getPath("userData") + "/settings.json";
return filepath;
}
This code lives in a helpers.js file that is being import through my electron_preload.js file.
I have no clue what or how to solve this.
import { contextBridge, ipcRenderer } from "electron";
const helpers= require("../src/helpers");
contextBridge.exposeInMainWorld("helpers", helpers);
Since you're executing the code in your preload environment, it is being run in the renderer process of the corresponding BrowserWindow. However, app is limited to the main process' execution scope (source) which is why your code throws the error.
You will have to expose the path via IPC.
// Main process, app.js or whatever
const { ipcMain, app } = require ("electron");
ipcMain.handle ("get-user-data-path", (event, ...args) => {
return app.getPath ("userData") + "/settings.json";
});
// In helpers.js
import fs from "fs";
const { ipcRenderer } = require("electron");
export async function getFilepath () {
return await ipcRenderer.invoke ("get-user-data-path");
}
For a more in-depth explanation, see the official Electron IPC tutorial.
(As a side note: I/O to the filesystem should probably be done by the main process, not the renderer. Worth considering from a security point of view.)
I have a very simple code structure like this
TestWorks.ts
const axios = require('axios');
export class TestWorks{
async getUsersList(param1:TestModel, userDetail:any){
console.log("BEGIN -- ... ");
And then this is my test class
MyTest.ts
const testworks = require("../src/interfaces/TestService/TestWorks");
it('Get Users', async () => {
var x = await testworks.getUsersList({}, {});
expect(x).to.be.an("object");
});
but I am seeing the following error, unable to figure out what the issue could be. The paths are definitely right, not an issue with the file paths of where the files are
Get Users:
TypeError: testworks.getUsersList is not a function
at C:\Users\xxxxxx\Documents\xxxxx\test\test-server.test.ts:53:28
testworks refers to the module (or whatever TypeScript exports) because you use require(). You should use import for TypeScript modules.
import { TestWorks } from '../src/interfaces/TestService/TestWorks';
Trying to find out if it's possible to run firebase cloud functions with native code (using N-API). I have a simple "hello world" example which works fine under emulator, however when I try to deploy it I get INVALID_ARGUMENT error:
status: {
code: 3
message: "INVALID_ARGUMENT"
}
That's is not very informative...
Just wondering if someone could shed some light on the situation. Thanks!
here is the function:
'use strict';
const functions = require('firebase-functions');
exports.helloWorld = functions.https.onRequest(async(request, response) => {
console.time('Program runtime');
const testAddon = require('bindings')('testaddon.node')
const {promisify} = require('util');
module.exports = testAddon;
const asyncCommand = testAddon.hello();
try {
const result = await asyncCommand;
console.log('CONTENT:', result);
response.send(result);
}
catch (err) {
console.log('ERROR:', err);
response.send('ERROR:', err);
}
console.timeEnd('Program runtime');
});
and corresponding C++ source:
#include <napi.h>
namespace functionexample {
std::string hello();
Napi::String HelloWrapped(const Napi::CallbackInfo& info);
Napi::Object Init(Napi::Env env, Napi::Object exports);
}
#include "functionexample.h"
std::string functionexample::hello(){
return "Hello World";
}
Napi::String functionexample::HelloWrapped(const Napi::CallbackInfo& info)
{
Napi::Env env = info.Env();
Napi::String returnValue = Napi::String::New(env, functionexample::hello());
return returnValue;
}
Napi::Object functionexample::Init(Napi::Env env, Napi::Object exports)
{
exports.Set(
"hello", Napi::Function::New(env, functionexample::HelloWrapped)
);
return exports;
}
i'd guess the problem is that testaddon.hello() doesn't return a promise so awaiting on it is a problem. if addon.hello() was an async javascript function then javascript would assure that it returned a promise, but it's a C++ function.
i haven't used promises from an addon before but this might help:
https://github.com/nodejs/node-addon-api/blob/master/doc/promises.md
It seems that the problem was with a version of the node engine. I've switched to node10 instead of node8 and my test function deploys properly and works as expected.
N-API has been marked like stable API starting from Node.js v8.6.0 so if you use an early version of the Node.js runtime you could meet problems like reported here. This is the reason because switching to Node.js version 10 all works well.