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.
Related
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 });
I want to get a variable from one .js file to another .js file. Right now I have
main.js
const balances = require('./balance');
console.log(balances.balanceBTC)
and I have
balance.js
const balanceBTC = () => {
return arrayCleaned[0];
};
exports.balanceBTC = balanceBTC;
And I am getting the error
const balances = require('./balance');
ReferenceError: require is not defined
I am running this code via windows PowerShell and the node version is: v14.10.1
NodeJS might be treating your code as an ES Module. And CommonJS variables like "require" are not available in ES modules. Try one of the below:
As mentioned
here,
declare require before using it.
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const balances = require('./balance');
[...]
If you have "type" : "module" in your package.json, remove it
It looks like the problem is coming from the environment where you are running your code.
Check the following links and you'lle find the answser:
Node | Require is not defined
https://www.thecrazyprogrammer.com/2020/05/require-is-not-defined.html
Require is not defined nodejs
https://github.com/nodejs/node/issues/33741
I have store this service account key (my-key.json) file in my downloads folder (ubuntu)
and then i run this command into my console
export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/my-key.json"
according to
google cloud. Now i am running this code but it throws me error.
const language = require('#google-cloud/language');
const quickstart = async function () {
// Instantiates a client
const client = new language.LanguageServiceClient();
// The text to analyze
const text = 'Hello, world!';
const document = {
content: text,
type: 'PLAIN_TEXT',
};
// Detects the sentiment of the text
const [result] = await client.analyzeSentiment({document: document});
const sentiment = result.documentSentiment;
console.log(`Text: ${text}`);
console.log(`Sentiment score: ${sentiment.score}`);
console.log(`Sentiment magnitude: ${sentiment.magnitude}`);
}
quickstart();
**ERORR** -
(node:13928) UnhandledPromiseRejectionWarning: Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.
at GoogleAuth.getApplicationDefaultAsync (/home/hardy/Documents/personal/project/node_modules/google-auth-library/build/src/auth/googleauth.js:154:19)
at processTicksAndRejections (internal/process/task_queues.js:94:5)
at async GoogleAuth.getClient (/home/hardy/Documents/personal/project/node_modules/google-auth-library/build/src/auth/googleauth.js:485:17)
at async GrpcClient._getCredentials (/home/hardy/Documents/personal/project/node_modules/google-gax/build/src/grpc.js:88:24)
at async GrpcClient.createStub (/home/hardy/Documents/personal/project/node_modules/google-gax/build/src/grpc.js:213:23)
If you are using node <file-name>.js to initialize your code, you should update the command to
GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/my-key.json" node <file-name>.js
This will make the GOOGLE_APPLICATION_CREDENTIALS available inside your node-environment.
However, as a long-term solution, I would suggest creating a .env file and storing the GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/my-key.json" in that file.
And then using the dotenv package at the beginning of your js file in the following manner:
require('dotenv').config();
You can also refer to https://stackoverflow.com/a/27090755/7743705 for understanding how to set environment variables in pacakge.json.
To be able to run using npm without setting credentials each time
"scripts": {
"start": "set GOOGLE_APPLICATION_CREDENTIALS=[PATH]/credentials.json&& nodemon server.js"
},
For further reason on how to use env you can visit How to set environment variables from within package.json? for more comprehensive answers.
So I’m doing a discord bot and decided to group my commands in separate files like help.js is one command and ping.js is another for example. Though now the problem is that the command cant find the module and so the code gives me an error like:
UnhandledPromiseRejectionWarning: ReferenceError: ms is not defined
Even though I have it defined in the top of the index file. (ms is a module that I need in my mute command to convert time)
const ms = require(“ms”);
I use this to get the commands:
try {
if (fs.existsSync(`./commands/${command}.js`)) {
let commandFile = require(`./commands/${command}.js`);
commandFile.run(client, message, args);
} else {
message.reply(`+${command} does not exist`)
}
And here is the ping command for example:
exports.run = async (client, message, args, level) => {
const m = await message.channel.send("Ping?");
m.edit(`Pong! Latency is ${m.createdTimestamp -message.createdTimestamp}ms. API Latency is ${Math.round(client.ping)}ms`);
}
I have checked that I have the node modules installed.
My question is, what am I doing wrong, why is it doing this & what do I do to fix this?
You need to require it in every file you have, unless it won't be available for you. You can also export it but you still need to import the main file and use it from there.
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.