Module is not recognized even if installed inside current folder - node.js

I use vscode for the IDE.
The project structure is :
The system is Linux, which is within a VPS : I am working from my vscode IDE using the remote development extension.
I created the node_modules folder inside the ethers folder, then I opened a terminal inside the ethers folder to install the ethers npm module : I made a right-click on the ethers folder, and clicked the option "Open in integrated terminal".
The module is installed inside the node_modules folder under the ethers folder.
When I test the code then I get error as the module is not known :
const { ethers } = require("ethers");
async function main() {
// Configuring the connection to an Ethereum node
const network = process.env.ETHEREUM_NETWORK;
const provider = new ethers.providers.InfuraProvider( // here is the line of bug
network
);
...
So why is the module not known ?

Related

Relative file paths in a global npm package

I have a command line utility that's installed as a global NPM package (privately, within our org).
I've noticed that file paths aren't actually relative to the installed location, but to the current working directory. In CommonJS I used __dirname but that's not valid with ESM.
So, when a user installs the package globally, and runs it, the following code errors because it's trying to use the current working directory.
fs.readFileSync('./templates/controller.ejs', 'utf8')
It works fine when I run the script from within the npm package folder itself. How I can always be sure it points to its install location?
EDIT: So far, the only way to do this is:
import { fileURLToPath } from 'url';
const dirname = fileURLToPath(new URL('.', import.meta.url));
const file = path.resolve(dirname, 'templates/controller.ejs')
fs.readFileSync(file, 'utf8')

vue + vite + ubuntu 20 bugs

I'm very confused.
I just saved my code to github from windows, where the vue.js app compiles successfully. But when opening exactly the same code in ubuntu, with the same versions of vite and vue, the app does not compile
I receive multiple errors when trying to apply destructuring.
In auth.js i have:
const test = new Test(); export default {test}
And, in another file I call this
import {test} from '/auth.js'
I received this:
No matching export in "src/auth.js" for import "test"
On windows everything works perfect. but when running "npm run dev" on Ubuntu I get this error.
I already tried:
-remove node_modules
-regenerate package-lock.json files
-update versions
the versions of vite, vue, node and npm are exactly the same on windows and ubuntu.
Some help?
You are exporting an object and attempting to destructure it when importing. However, this is the syntax for importing named exports and since you don't have a named export the error is occurring.
You should either do
export default test
import test from './auth.js'
Or
export { test }
import { test } from './auth.js'

how to dynamically import a node module after installing it during runtime

I have a node script that is suppose to work as a CLI doing the following:
Search node modules for a required module based on the CLI command entered
If not found, use node's exec to run npm install "dynamicModule"
after the module is installed, dynamically import it using await import('dynamicModule')
The code is able to discover if the module is available and install it successfully if not, however.. when trying to then import the module, Node complains it is not found. The module does end up in node_modules and if I re-run the code (the check now says the module IS installed) it is able to dynamically import it just fine.
Is there a way to dynamically import a node module at runtime that is ALSO installed at runtime?
Code below:
async getProviderPlugin(provider: string) {
/**
* Determine if the user has passed a provider and prompt them if not
*/
const checkSpinner = ora(`Checking for ${provider} module...`)
const hasPlugin = moduleIsAvailable(`${provider}-provider-plugin`)
console.log(`plugin exists: ${hasPlugin}`)
if (!hasPlugin) {
this.log(`${provider} plugin does not exist, installing now`)
const installOra = ora(`Installing ${provider} plugin`)
const exec = require('child_process').exec
await exec(`yalc add ${provider}-provider-plugin`)
installOra.succeed(`${provider} plugin installed successfully!`)
// execute npm install
}
checkSpinner.succeed(`${provider} module check complete`)
return import(`${provider}-provider-plugin`)
}

Using npm as custom plugin manager?

Think of sublime text, where you can install or uninstall plugins. I want that for my app, and I want to use npm/github to do it.
Maybe I'll require that your package starts with myapp- to be considered a plugin for my app. How can I search npm based on that, and also install/update packages into the folder I want (not node_modules) and ideally it should work even if the person doesn't have npm installed (using an http api?).
Plugins for my app go into plugins/plugin-name folder, all I need to do is download their git source into that folder
I have created a project to solve similar problems. See live-plugin-manager.
You can install, uninstall and load plugins from npm at runtime.
import {PluginManager} from "live-plugin-manager";
import * as path from "path";
const manager = new PluginManager({
pluginsPath: path.join(__dirname, "plugins")
});
async function run() {
await manager.installFromNpm("moment");
const moment = manager.require("moment");
console.log(moment().format());
await manager.uninstall("moment");
}
run();
In the above code I install moment package at runtime, load and execute it. Here I have used typescript, but the same can be written with plain javascript.
Plugins are installed inside the directory specified in the PluginManager constructor or in the plugins directory if not specified.
I just created a great module, for enhancements like your proposal:
https://www.npmjs.com/package/#kawix/core
You can read the README.md, for try understand the usage, i will add a basic example:
> npm install -g #kawix/core
> kwcore "https://raw.githubusercontent.com/voxsoftware/kawix-core/master/example/npmrequire/express.js"
And this is the content of file https://raw.githubusercontent.com/voxsoftware/kawix-core/master/example/npmrequire/express.js
// this will download the npm module and make a local cache
import express from 'npm://express#^4.16.4'
var app = express()
app.get('/', function (req, res) {
res.send('Hello World')
})
app.listen(3000)
console.log("Listening on 3000")
https://api-docs.npms.io/ has an http API for searching npm packages.
Which can be used like this: https://api.npms.io/v2/search?q=keywords:myapp to get all plugins for myapp
To actually download/install an npm package into any folder, I found an npm package called download-npm-package that lets me do it in code

Node global module getting current run directory

I'm trying to create a node module that has the ability to be installed globally using npm install -g mymodulename. I've got everything in the module working fine if I run node index.js in the directory of the module, but now I want to make it so that I can publish it to NPM, and it can be installed and run from any directory.
There is some code in my module that looks at certain files in the directory that it is run in. I'm finding that when I do npm install -g ./ and then go into a different directory for a test, then run my-module-command, the relative path that it is reading is from that of where my module got installed (i.e. /usr/local/bin/my-module), not the directory that I'm running it in.
How can my module that is installed globally know where it is being run from? To give an example, I am trying to read the package.json file in the directory I'm in. And it is reading the package.json file of /usr/local/bin/my-module/package.json
I've tried:
__dirname
process.args[1]
process.cwd()
And just calling straight to require('./package.json') directly and none of those work.
Edit here's some code that's breaking in index.js:
#!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var currentDir = path.dirname(require.main.filename);
fs.exists(`${currentDir}/node_modules`, function(dir) {
if (!dir) throw 'node_modules does not exist';
// do stuff
});
In my package.json:
...
"bin": {
"my-module": "./index.js"
},
...
I try to do npm install -g ./ in the project directory, and then I cd into a different directory called /Users/me/Projects/different-project, where another npm project is, and run my-module, and I get node_modules does not exist. When I log out currentDir, I get /usr/local/lib/node_modules/my-module where I'm expecting is to see /Users/me/Projects/different-project.
Have you tried using ./ at the start of your file path? That should give you the current working directory (or calling process.cwd() would work too).
In your case, your code would look like:
fs.exists(`./node_modules`, function(dir) {
if (!dir) throw 'node_modules does not exist';
// do stuff
});
I can see some comments already mention this. Maybe I'm misunderstanding the question? I just had a case where I needed a global module to get the directory I'm running the script from and what I suggested above worked like a charm.

Resources