My Javascript file won't run because of bigint error - javascript

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 });

Related

500 process is not defined ReferenceError: process is not defined

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.

Javascript promise never resolves

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.

get gulp version in gulpfile

Is there a way to detect what version of Gulp is running (available to utilize in a gulpfile)?
I've got two separate gulpfile's I'm using amongst different environments, some that require v3 and some v4. For easier version control, I would prefer it if I could combine those files and not have to deal with different file names in different environments to eliminate confusion between multiple developers. Obviously to accomplish this I would need the script to differentiate between versions.
Alternatively to #alireza.salemian's solution, you could try to run the command line version command in javascript:
Depending on your JavaScript backend, your code may vary slightly, but inspired by this post you could run it as below:
const execSync = require('child_process').execSync;
// import { execSync } from 'child_process'; // replace ^ if using ES modules
const output = execSync('gulp -v', { encoding: 'utf-8' }); // the default is 'buffer'
const str_pos = output.search('Local version') + 14;
const gulp_version = output.substring( str_pos, str_pos + 5 );
console.log( 'Gulp version: ' + gulp_version );
You can read package.json and find gulp version
const pkgJson = fs.readFileSync('./package.json', { encoding: 'utf8' });
const pkg = JSON.parse(pkgJson);
const gulpVersion = pkg['devDependencies']['gulp'];
It may not be the best solution, but you can quickly determine the gulp version.

"fetch is not found globally and no fetcher passed" when using spacejam in meteor

I'm writing unit tests to check my api. Before I merged my git test branch with my dev branch everything was fine, but then I started to get this error:
App running at: http://localhost:4096/
spacejam: meteor is ready
spacejam: spawning phantomjs
phantomjs: Running tests at http://localhost:4096/local using test-in-console
phantomjs: Error: fetch is not found globally and no fetcher passed, to fix pass a fetch for
your environment like https://www.npmjs.com/package/unfetch.
For example:
import fetch from 'unfetch';
import { createHttpLink } from 'apollo-link-http';
const link = createHttpLink({ uri: '/graphql', fetch: fetch });
Here's a part of my api.test.js file:
describe('GraphQL API for users', () => {
before(() => {
StubCollections.add([Meteor.users]);
StubCollections.stub();
});
after(() => {
StubCollections.restore();
});
it('should do the work', () => {
const x = 'hello';
expect(x).to.be.a('string');
});
});
The funniest thing is that I don't even have graphql in my tests (although, I use it in my meteor package)
Unfortunately, I didn't to find enough information (apart from apollo-link-http docs that has examples, but still puzzles me). I did try to use that example, but it didn't help and I still get the same error
I got the same error importing a npm module doing graphql queries into my React application. The app was compiling but tests were failing since window.fetch is not available in the Node.js runtime.
I solved the problem by installing node-fetch https://www.npmjs.com/package/node-fetch and adding the following declarations to jest.config.js:
const fetch = require('node-fetch')
global.fetch = fetch
global.window = global
global.Headers = fetch.Headers
global.Request = fetch.Request
global.Response = fetch.Response
global.location = { hostname: '' }
Doing so we instruct Jest on how to handle window.fetch when it executes frontend code in the Node.js runtime.
If you're using nodejs do the following:
Install node-fetch
npm install --save node-fetch
Add the line below to index.js:
global.fetch = require('node-fetch');
The problem is this: fetch is defined when you are in the browser, and is available as fetch, or even window.fetch
In the server it is not defined, and either needs to be imported explicity, or a polyfill like https://www.npmjs.com/package/unfetch (as suggested in the error message) needs to be imported by your test code to make the problem go away.

Is it feasible to use web worker (multi-threading) in Angular and Typescript in NativeScript?

I'm currently develop an App that is based on NativeScript and Angular2.
My screen freeze for while when my App fetching data through HTTP, and I'd like to put the fetching action into another thread.
I did a lot of search on the web, and all I got is the code in javascript like the official doc - https://docs.nativescript.org/angular/core-concepts/multithreading-model.html
Is there any way to implement the muli-threading with WebWorker in "Typescript"(which contain the support of Angular injected HTTP service) instead of the "Javascript" code(the code from the official doc)
It's appreciated if someone could give me some guide or hint, and it'll be great if I could got some relative example code.
Thanks.
There shouldn't be any big draw back for using WebWorkers in {N} + Angular but be aware that currently the WebWorker is not "exactly" compatible with Angular AoT compilation.
For me when creating an WebwWrker (var myWorker = new Worker('~/web.worker.js');) throws and error after bundling the application with AoT. I have seen soem talk about this in the community and possible the way to fix this is by editing the webpack.common.js and adding an "loaded" like so:
{
test: /\.worker.js$/,
loaders: [
"worker-loader"
]
}
Disclaimer: I have not tried this approach for fixing the error.
If someone have some problems adding workers in Nativescript with Angular and Webpack, you must follow the steps listed here.
Keep special caution in the next steps:
When you import the worker, the route to the worker file comes after nativescript-worker-loader!.
In the webpack.config.js keep caution adding this piece of code:
{
test: /.ts$/, exclude: /.worker.ts$/, use: [
"nativescript-dev-webpack/moduleid-compat-loader",
"#ngtools/webpack",
]
},
because is probable that you already have configured the AoT compilation, like this:
{
test: /(?:\.ngfactory\.js|\.ngstyle\.js|\.ts)$/,
use: [
"nativescript-dev-webpack/moduleid-compat-loader",
"#ngtools/webpack",
]
},
and you only need to add the exclude: /.worker.ts$/,
Finally, there is an example of a worker, in this case it use an Android native library:
example.worker.ts:
import "globals";
const context: Worker = self as any;
declare const HPRTAndroidSDK;
context.onmessage = msg => {
let request = msg.data;
let port = request.port;
let result = HPRTAndroidSDK.HPRTPrinterHelper.PortOpen("Bluetooth," + port.portName);
context.postMessage(result);
};
example.component.ts (../../workers/example.worker is the relative route to my worker):
import * as PrinterBTWorker from "nativescript-worker-loader!../../workers/example.worker";
import ...
connect(printer: HPRTPrinter): Observable<boolean> {
if (this.isConnected()){
this.disconnect(); //Disconnect first if it's already connected
}
return Observable.create((observer) => {
const worker = new PrinterBTWorker();
worker.postMessage({ port: printer });
worker.onmessage = (msg: any) => {
worker.terminate();
if (msg.data == 0) { // 0: Connected, -1: Disconnected
observer.next(true);
}
else {
observer.next(false);
}
};
worker.onerror = (err) => {
worker.terminate();
observer.next(false);
}
}).pipe(timeout(5000), catchError(err => of(false)));
}
Note: I use an Observable to make my call to the worker async and to add a timeout to the call to the native code, because in the case that it is not possible to connect to the printer (ex. it's turned off), it takes almost 10 seconds to notify, and this caused in my case the frezing of the app for all that time.
Important: It seem that it's necessary to run again the code manually every time that a change is made, because the worker isn't compiled using AoT.

Categories