Check if a particular NPM package is installed globally - node.js

I'm trying to check if a particular npm package is installed/available globally using Nodejs. I managed to list the global dependencies/packages through the npm command npm list -g --depth=0. So i tried out this piece of code.
const {exec} = require("child_process");
exec("npm list -g --depth=0",(err, stdout, stderr) => {
if (err) {
console.error(err);
return;
}
console.log(stdout);
});
Then it throws an error like this
PS: i also tried to use npm list -g --depth=0 | grep nodemon but i cannot use it on command prompt. So that is wrong in the above code? how can check whether if package installed globally in any OS using nodejs?

The code in your npm.js file looks OK and should run successfully - that's assuming that:
when you run npm list -g --depth=0 directly in your CLI you do get the desired result.
The version of nodejs you're running does support ES6 features, such as Object Destructuring and Arrow functions.
The problem is the filenaming of the nodejs script - Don't name it npm.js.
You need to rename the file as something else, such as, e.g. get-global-pkgs.js.
Then cd to the directory where get-global-pkgs.js resides, and run either of the following commands:
node get-global-pkgs.js
or
node get-global-pkgs
i.e without the .js suffix
Note: Naming the file npm.js only seems to be an issue when the files content utilizes exec() and/or spawn() methods, and the given command results in a http(s) GET request.

Related

Calling npx from a node.js file

I've tried using exec with a bash file, I've tried using direct calls, I've tried digging into npm and npx docs but there seems to be no answer to this question: how can an npx call be triggered form node.js code?
An answer that triggers the same functionality as an npx call without actually being written as an npx call would also be acceptable.
I am not really sure where your problem is...
how you call npx scripts in general?
running shell commands from within node?
Running specifically npx commands? Is there an error you get?
The most widespread way to run shell commands would be child_process, and I don't know why you couldn't just put an npx command in there (I just tested it with npx --help and that worked):
const { exec } = require("child_process");
exec("echo Hello World", (err, stdout, stderr) => {
if (err) {
console.error();
console.error("Error:");
console.error(err);
console.error();
}
console.log(stdout);
console.error(stderr);
});
Now, this might be what you meant by "tried using exec", and you just get an error doing that. Of course, it would be helpful to have that error in that case, but maybe it is that npx isn't found.
Make sure you have npx installed then - maybe it's just npms virutal environment that can't access it, so you could use npm install npx to install it into there. If you are running it with npm, make sure it's installed globally: npm install -g npx.
If it is a different problem, please provide more information on what exactly you are lacking or potential errors you are getting.

what is the mpv option mean in Node?

I wanted to use mpv option for my Node project, but it seems the option is reserved already.
$ npm --mpv
output : 6.5.0
what's the mpv option pointing?
and is there any way I can use the mpv option for my Node project?
TLDR
You can use --mpv as an argument to your node.js project. There is nothing that would make it not work.
Example:
// example.js
if (process.argv[2] == '--mpv') {
console.log('hooray');
}
The script above would print hooray if you run it with --mpv as argument:
$ node example.js --mpv
hooray
Details:
The npm command treats -- options the same as - options for some reason. Thus the command:
npm --mpv
is somehow interpreted as
npm -m -p -v
Neither m nor p does anything and are ignored instead of throwing errors. But the v option prints out the version number. Thus the command is the same as
npm -v
Note that npm is not node.js. Node does not behave the same and would throw an error:
$ node --mpv
node: bad option: --mpv
Indeed, the npm project explicitly declares themselves to not be a node package manager even though npm is now managed by the node.js project directly. Npm can deploy packages written in other languages such as Ruby (such as the original Sass project, now re-written in js), Python or even C and assembly.
--mpv is not a reserved option -- nor is any other sequence. node itself takes many options, but anything on the command line after your script name is passed directly to process.argv.
In other words, the following have two different behaviors:
$ node --inspect script.js # enables node's built-in debugger; process.argv = ['node', 'script.js']
$ node script.js --inspect # process.argv = ['node', 'script.js', '--inspect']
Also, --mpv does not appear anywhere in the npm documentation. I suspect that the npm CLI is misinterperting --mpv as -v and printing its version number.

CSSO npm not working while others are

I’m new to Node.js & npm and am trying to figure out why the uglifyjs module is working while the csso module is not.
i recently moved my global install to following location
/Users/myname/.node_modules_global/bin/npm
via this tutorial’s recommendation.
https://www.sitepoint.com/beginners-guide-node-package-manager/
to show they are both installed globally i do this via the command line
npm list -g --depth=0
and i get this result
/Users/myname/.node_modules_global/lib
csso#3.1.1
npm#5.3.0
uglify-js#3.0.25
for testing purposes i navigate to a local static site and run the commands using the CLI.
the uglifyjs command works. but when running the command for csso which is
$csso style.css style.min.css
i get this error
bash: csso: command not found
i’m at a loss how to even troubleshoot except this.
I think you are missing the CLI version. Please try:
npm i csso-cli
to install it.

node.js: cannot find module 'request'

I installed request module, and getting the error:
module.js:340
throw err;
^
Error: Cannot find module 'request'
i've read all the posts about this error, and understand that this is because module requests is not globally found, but i've already tried the 2 suggestions
npm install request -g
should this install it in /usr/loca/bin ? because i don't see it there.
and
sudo npm link
/usr/local/lib/node_modules/request -> /Users/soulsonic/dev/sandbox/node_test/request
i restarted terminal after each command, but keep getting the cannot find module error.
update
there must have been some sort of conflict in my initial directory, because "npm install request" was not adding "request" under node_modules (there 10 others in there) ..
after switching to a new directory it just worked.
if i run it with -g switch, i do see it bing installed to /usr/local/lib/node_modules/request.
it seems that i just need to update my profile so that above path is automatically added.
Go to directory of your project
mkdir TestProject
cd TestProject
Make this directory a root of your project (this will create a default package.json file)
npm init --yes
Install required npm module and save it as a project dependency (it will appear in package.json)
npm install request --save
Create a test.js file in project directory with code from package example
var request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body); // Print the google web page.
}
});
Your project directory should look like this
TestProject/
- node_modules/
- package.json
- test.js
Now just run node inside your project directory
node test.js
You should simply install request locally within your project.
Just cd to the folder containing your js file and run
npm install request
I had same problem, for me npm install request --save solved the problem. Hope it helps.
I have met the same problem as I install it globally, then I try to install it locally, and it work.
if some module you cant find, try with Static URI, for example:
var Mustache = require("/media/fabio/Datos/Express/2_required_a_module/node_modules/mustache/mustache.js");
This example, run on Ubuntu Gnome 16.04 of 64 bits, node -v: v4.2.6, npm: 3.5.2
Refer to: Blog of Ben Nadel
I tried installing the module locally with version and it worked!!
npm install request#^2.*
Thanks.
I was running into the same problem, here is how I got it working..
open terminal:
mkdir testExpress
cd testExpress
npm install request
or
sudo npm install -g request // If you would like to globally install.
now don't use
node app.js or node test.js, you will run into this problem doing so. You can also print the problem that is being cause by using this command.. "node -p app.js"
The above command to start nodeJs has been deprecated. Instead use
npm start
You should see this..
testExpress#0.0.0 start /Users/{username}/testExpress
node ./bin/www
Open your web browser and check for localhost:3000
You should see Express install (Welcome to Express)
ReferenceError: Can't find variable: require.
You have installed "npm", you can run as normal the script to a "localhost" "127.0.0.1".
When you use the http.clientRequest() with "options" in a "npm" you need to install "RequireJS" inside of the module.
A module is any file or directory in the node_modules directory that can be loaded by the Node.
Install "RequiereJS" for to make work the http.clientRequest(options).

How to use a node module outside of node?

I installed the sass node module through npm and want to use it to compile some scss stylesheets which are not in a node environment.
Ideally I want to be able to use it like the coffeescript compiler
sass -cw somestylesheet.scss
But anything that gets me close to there will do.
I don't see any commandline utility. Is there some sort of standard way to do this sort of thing with node?
I'm sure you're already hacking together a little sass-compiler script, but here is some more background info:
To install a module globally in node using npm, npm reads the "bin" hash in package.json, to find a number of global names mapped to their corresponding scripts.
Here is an example I took from express:
{
"name" : "express"
...
"bin": { "express": "./bin/express" },
...
}
This tells npm to make the express script globally available, when you install the package with npm install -g <package-name>
I've checked https://github.com/andrew/node-sass/blob/master/package.json and it has no "bin" hash in its package.json, so you'll have to write one yourself.
As #peter-lyons has said, you start an executable node script with
#!/usr/bin/env node
your code
depending on the operating system you are using, you might also have to make the script executable with chmod +x yourScript. Then you should just be able to execute your script from any console, if you either put it on the global path, or if you call it as ./yourScript.

Resources