Trouble access node_modules on javascript - javascript

I have confusion about access node_modules that can be used in JavaScript. for this does anyone can give an example to call modul.export contained in the folder node_module (after install packet with NPM - nodejs) ?
tree structure file :
folder ethereum any folder node_modules , file index.html (for call module.export) , package-lock.json , package.json
package.json file :
enter link description here
so this way, I've installed "npm install web3". Now, when I call a function from web3 like for example in a program like this :
var Web3=require('web3');
if (typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider);
} else {
web3 = new Web3(new Web3.providers.HttpProvider("https://rinkeby.infura.io/metamask"));
}
console.log(web3);
Then output errors like this :
enter image description here

The web3 package can either be installed through npm with npm install web3 or is exposed as a global web3 if you import it like:
<script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js/dist/web3.min.js"></script>
It can either be run as a global exposed by the <script></script> tag or as a node package that needs to be bundled first.
Your error code require is not defined tells you that node is not running your code, but something else is consuming your code. Try to bundle your code to something the browser understands, or only use the global web3 to interact with the package.
Read more about bundles here: https://docs.npmjs.com/getting-started/packages

If I understand correctly, you are missing a big piece of the puzzle here.
You need to compile your code for the browser to be able to run it. Try reading up on this question

Related

'process' var is undefined in Vue / Typescript component

I am having a problem getting .env variables working in my Vue app. After npm install process this was the only syntax that didn't throw an error when trying to import.
import * as process from 'process';
Before this I also had the following error:
Cannot find name 'process'. Do you need to install type definitions for node? Try `npm i --save-dev #types/node`.
I ran this install and added "node" to types in my tsconfig file.
I have a member variable defined like so,
const testVar = process.env.TEST_VAR
and have tried both TEST_VAR=just test and TEST_VAR="just test" inside my .env file.
The .env file itself is placed in the root folder of the project, ie. outside the src folder, but I have tried placing it inside the src folder also.
Despite all that, the var is coming back undefined.
mounted(){
console.log('ENV TEST -> ', this.testVar)
alert(`ENV2 : ${this.testVar}`)
...
}
I'd be very grateful for any help solving this. Thanks!
Only variables that start with VUE_APP_ will be statically embedded into the client bundle. Vue docs
And then it will be accessible in the components
mounted() {
console.log(process.env.VUE_APP_TEST_VAR)
}

npm selenium does not see my chromedriver

I am using selenium-webdriver module on npm and my code is =
const selenium = require('selenium-webdriver');
const { Builder, By, Key } = selenium;
(async() => {
const driver = await new Builder().forBrowser('chrome').withCapabilities(selenium.Capabilities.chrome().set('chrome.binary', './drivers/chromedriver.exe')).build();
})();
It gives me the error Error: The ChromeDriver could not be found on the current PATH. I downloaded chromedriver then try both using .withCapabilities(that part is still inside the code above) and export PATH=$PATH: but both not worked still giving same error I have chromedriver in a folder called drivers and that folder is on same folder with my index.js file I think my path writing is wrong but I really don't know how to do it can someone help?
As #Max Daroshchanka suggested in the comments section, first thing is that you must have the path to the executable chrome.exe for the "chrome.binary" option.
Secondly, I will suggest that you have the same version for chromedriver.exe and your chrome.exe. I faced the same issue because I was not having the same version.
Now the following is something that did not work for me. Could not be the case with you.
Thirdly, I will also suggest that instead of relying on the node.js (or any package manager's) library (this gets created when you perform npm install, for every dependency there is a /lib folder created that has the executable) to add the required chromedriver.exe file. What I mean is manually download the required version driver file from here:
http://chromedriver.storage.googleapis.com/index.html
and add this downloaded extracted path to the PATH env variable.

Is there a way to get autocomplete for .proto JavaScript generated code?

I've written a simple .proto file
syntax = "proto3";
message Event {
optional string name = 1;
}
I've downloaded the protoc linux compiler (protoc-3.19.3-linux-x86_64.zip) and installed it in my local machine outside of the project's folder.
Then I installed the core runtime dependency with
$ npm i google-protobuf
My package.json shows:
"google-protobuf": "^3.19.3",
I then ran this line to generate the JS code from the .proto file
$ protoc --js_out=import_style=commonjs,binary:. protos/event.proto
It outputs some generated code that I can import with
const Schema = require("./protos/event_pb");
by inspecting Schema.Event I can see that my prop .name is in there, but I can't get any autocomplete going. Is there a way to achieve this?
Turns out there are some well-maintained npm packages that handle these things.
https://www.npmjs.com/package/protobufjs
or
https://www.npmjs.com/package/ts-proto

How to use a web-worker from an npm library into main webpack project

My project structure is like this:
moduleA -> Library that i publish to npm using Rollup
projectA -> My gatsby project that installs moduleA and uses it.
I'm using this library to bundle my workers with my other library code into the dist folder: https://github.com/darionco/rollup-plugin-web-worker-loader
Module A code:
workers/index.js
let webWorker = null;
if (typeof window !== "undefined") {
webWorker = new Worker(new URL("./my.worker.js", import.meta.url), {
type: "module",
});
}
export default webWorker;
workers/my.worker.js
self.onmessage = (message) => {
console.log("hii");
self.postMessage("yes");
};
When I build the above library the result is this:
So you can see that the workers are correctly in the library's dist now. This all works great.
If we take a look into index.modern.module.js you can see this is the output for the worker code:
if (typeof window !== "undefined") {
webWorker = new Worker(new URL("my.worker-f73c7cd4.js", import.meta.url), {
type: "module"
});
}
Now in my main project I have this webpack rule to convert the import.meta.url to a path otherwise webpack crashes as it does not recognize import.meta.url:
config.module.rules.push({
test: /\.jsx?$/,
loader: require.resolve("#open-wc/webpack-import-meta-loader"),
});
I now run my main react project (which is built in gatsby & webpack) and this is the output in index.modern.module.js:
if (typeof window !== "undefined") {
webWorker = new Worker(new URL("my.worker-8e6a623b.js", ({ url: getAbsoluteUrl('node_modules/#tracktak/dcf-react/dist/index.modern.module.js') }).url), {
type: "module"
});
}
Here's the network request, you can see it loans in but I'm pretty sure the path is wrong. It's just saying a 200 ok because it's going to 404 page I think:
And it gives me a console error:
Failed to load module script: The server responded with a non-JavaScript MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.
So, my question is. How do I load the web worker to the public folder for my Gatsby project (projectA). Do I need to use something like worker-loader here? I'm just not sure how it can work here because it's in my npm module and NOT in my project.
Any help would be great and I'd award a bounty!
Thanks
EDIT: It seems like worker-plugin is getting my closer to the solution. If I use this in my main project and modify the web workers in the dist output from this: new URL("my.worker-8e6a623b.js", ({ url: getAbsoluteUrl('node_modules/#tracktak/dcf-react/dist/index.modern.module.js') }).url) to this: new URL("my.worker-8e6a623b.js") it works fine as worker-plugin only accepts string arguments.
However this isn't a sustainable solution because obviously I don't want to modify dist files.
Updated:
Verify the dist folder contents are correct. I'm surprised to see files from old builds (multiple hash ids). Clean folder, then generate all scripts (for performance reasons, you might want to only do this on production builds.)
Then when you npm publish the files, verify npm picked up what you expect.
There's an alternate way to make sure it's not related to npm's selective file bundling. Use the GitHub repo URL to npm install <github repo URL>.
Original response:
I believe you need worker-loader.
I've used comlink & worker-loader to help smooth over Webpack worker bundling.

Node Modules with VUE-CLI

I am creating vue-cli project and everything works file, but when i try to install new module it show me error after install :
This dependency was not found:
* fs in ./~/babel-loader/lib!./~/vue-loader/lib/selector.js?type=script&index=0!./src/components/Index.vue, ./~/mp3-duration/index.js and 1 other
To install it, you can run: npm install --save fs
I tried multiple times to confirm but still an error, in the node_modules folder there is a library.
I am installing this module and using :
const musicdata = require('musicmetadata');
After add above code i am writing this :
getDuration(file) {
fs.createReadStream(file), (err, metadata) => {
if (err) throw err;
console.log(metadata)
}
}
But getting an error as I specified above, I want a single page website but want some node_modules to get some information, how do I include these modules?
Thanks
I would say this is because fs is a specifically for reading files in a Node application and you're running it in the browser. You could look into the FileReader API which helps read local files (and I would imagine your application's files). Worst case, someone has written an NPM package for it.

Categories