Why I'm getting an error when creating a npm package - node.js

I am new with NPM. Below hackerrank question is asking next:
Create the file package.json using npm commands
The name of the app should be npm_package.
Tha start point will be index.js.
The project should have the following elements of dependencecies
Install the latest version of react
Lodash with major version 4 and minor version 17
Redux with Major version 4
Mocha dor testing in Dev
Eslint with major version 6 in Dev
So, I tried these commands but it was marked as fail
mkdir npm_package
cd npm_package
npm init
npm install react --save
npm install lodash#4.17.0 --save
npm install redux#4.0.0 --save
npm install mocha --save-dev
npm install eslint#6.0.0 --save-dev
What I am missing? Below is the result:
grep: /projects/challenge/package.json: No such file or directory
grep: /projects/challenge/package.json: No such file or directory
find: ‘/projects/challenge/node_modules’: No such file or directory
grep: /projects/challenge/package.json: No such file or directory
Test cases executed = 4
PASS = 0 FAIL=4
**challenge/npm_package$ ls**
**node_modules package.json package-lock.json**

To initialize to the default package.json we have to supply the -y flag:
npm init -y

Related

npm install by default tries to install globally

When performing npm install on a folder, the package is installed on c:\Users\<user>\node-modules instead of .\<project folder>\node-modules
I've tried to update npm config save=false but this didn't solve the problem
PS C:\Users\danielk\Documents\udemy_nodejs\FirstExpressApp> npm install express
npm WARN danielk No description
npm WARN danielk No repository field.
npm WARN danielk No license field.
+ express#4.17.1
updated 1 package and audited 126 packages in 2.004s
found 0 vulnerabilities
PS C:\Users\danielk\Documents\udemy_nodejs\FirstExpressApp> dir
Directory: C:\Users\danielk\Documents\udemy_nodejs\FirstExpressApp
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 21/08/2019 7:54 AM 27 app.js
When doing npm install express in the project folder, I would expect the node-modules subfolder to be created in the project folder and the express module to be installed in the node-modules subfolder. However its created in C:\Users\danielk\node-modules.
Could anyone help on what is wrong and how this can be fixed?
When you do npm install, npm actually installs the package to the "npm project" you are currently in. See the following example:
eric_#Eric-Dev-Laptop MINGW64 ~/Desktop/mixed/stackoverflow
$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (stackoverflow)
[...Truncated...]
Is this OK? (yes)
eric_#Eric-Dev-Laptop MINGW64 ~/Desktop/mixed/stackoverflow
$ mkdir child
eric_#Eric-Dev-Laptop MINGW64 ~/Desktop/mixed/stackoverflow
$ cd child/
eric_#Eric-Dev-Laptop MINGW64 ~/Desktop/mixed/stackoverflow/child
$ npm install express
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN stackoverflow#1.0.0 No description
npm WARN stackoverflow#1.0.0 No repository field.
+ express#4.17.1
added 50 packages from 37 contributors and audited 126 packages in 3.021s
found 0 vulnerabilities
eric_#Eric-Dev-Laptop MINGW64 ~/Desktop/mixed/stackoverflow/child
$ ls
eric_#Eric-Dev-Laptop MINGW64 ~/Desktop/mixed/stackoverflow/child
$ ls ..
child/ node_modules/ package.json package-lock.json
eric_#Eric-Dev-Laptop MINGW64 ~/Desktop/mixed/stackoverflow/child
$ ls ../node_modules/
accepts/ escape-html/ mime/ safer-buffer/
array-flatten/ etag/ mime-db/ send/
body-parser/ express/ mime-types/ serve-static/
bytes/ finalhandler/ ms/ setprototypeof/
content-disposition/ forwarded/ negotiator/ statuses/
content-type/ fresh/ on-finished/ toidentifier/
cookie/ http-errors/ parseurl/ type-is/
cookie-signature/ iconv-lite/ path-to-regexp/ unpipe/
debug/ inherits/ proxy-addr/ utils-merge/
depd/ ipaddr.js/ qs/ vary/
destroy/ media-typer/ range-parser/
ee-first/ merge-descriptors/ raw-body/
encodeurl/ methods/ safe-buffer/
What happens is, I made a stackoverflow folder, initialized an "npm project" there with npm init, and cd into child folder. When I do npm install express inside, the express module will inadvertently get installed to stackoverflow/node_module. This is such that when you are making a program, e.g. myprogram, and even when you are in some subfolder inside (e.g. myprogram/lib/) and you perform npm install, the module will still be installed to myprogram.
Comparing this to your case, this is probably because your C:\Users\danielk\ is already an npm project, so when you are in C:\Users\danielk\Documents\udemy_nodejs\FirstExpressApp , npm thinks you are in the C:\Users\danielk\ project and thus save the express module there.
As for why C:\Users\danielk\ became an npm project, is it either you manually did npm init there before, or you performed your first npm install there, and C:\Users\danielk\node_modules is created, marking it an npm project.
And one more thing, that express is not installed "globally", you do "global" install by npm install express -g (well though for express there is no use to install it globally). Your case is just the package getting "installed in the home directory".

How to update all Node.js modules automatically?

During my work with the Node.js environment, I faced the issue of version maintenance of Node.js modules. I would like to be sure that all internal Node.js modules are updated.
Many of existing manuals focus just on how to update Node.js modules, but not how to automate such routine.
How to update all Node.js modules automatically to the latest version?
Ideally, it should be some script, job, or task.
To update all Node.js modules manually:
Open console with administrative permissions
Go to Node.js installation folder: cd C:\Program Files\nodejs
Update npm: npm i npm#latest
Go to modules folder: cd C:\Program Files\nodejs\node_modules\npm
Install all desired modules: npm i %MODULE_NAME%#latest
Install update manager: npm i npm-check#latest -g
Available updates for locally installed modules: npm-check -u
Available updates for globally installed modules: npm-check -u -g
Recursive update of all locally installed modules: npm update --depth 9999 --dev
Recursive update of all globally installed modules: npm update --depth 9999 --dev -g
Clear the cache: npm cache clear --force
To update all Node.js modules automatically:
Create a package.json:
{
"_cmd-update-all-modules": "npm run update-all-modules",
"scripts": {
"create-global-node-modules-folder": "if not exist \"%appdata%\\npm\\node_modules\" mkdir %appdata%\\npm\\node_modules",
"npm-i-g": "npm i npm#latest -g",
"npm-check-i-g": "npm i npm-check#latest -g",
"npm-check-u-l": "npm-check \"C:\\Program Files\\nodejs\\node_modules\\npm\" -y",
"npm-check-u-g": "npm-check \"C:\\Program Files\\nodejs\\node_modules\\npm\" -y -g",
"npm-deep-update-l": "npm update --depth 9999 --dev",
"npm-deep-update-g": "npm update --depth 9999 --dev -g",
"npm-cache-clear": "npm cache clear --force",
"update-all-modules": "npm run create-global-node-modules-folder && npm run npm-i-g && npm run npm-check-i-g && npm run npm-check-u-l && npm run npm-check-u-g && npm run npm-deep-update-l && npm run npm-deep-update-g && npm run npm-cache-clear"
}
}
Specify all desired modules to be installed in the scripts section
Make sure the folder with Node.js, e.g. C:\Program Files\nodejs, is added to the PATH through the Environment Variables
Copy package.json to the folder with Node.js from the step #3
Open console with the administrative permissions
In the console, go to the folder with package.json from the step #3
Execute npm run update-all-modules
Both of these approaches allow you keeping all Node.js modules updated to the latest version, wherever it is installed locally or globally.
To run this package.json, call npm run update-all-modules, stored as a hint inside of the _cmd-update-all-modules property.
Just need to follow below commands
npm install -g npm-check-updates
ncu -u
npm update
npm install
Explanation:
To update all packages to a new major version, install the npm-check-updates package globally.
This will upgrade all the version hints in the package.json file, to dependencies and devDependencies, so npm can install the new major version.
You are now ready to run the update.
Now install updated packages. Flag --force sometimes required if already exists some conflicting packages.
Reference link: https://nodejs.dev/learn/update-all-the-nodejs-dependencies-to-their-latest-version
I went to https://nodejs.org/en/download/ downloaded the installer and repaired the installation, all warnings and errors disapeared. hope helps someone :P

Clarification of the --save option for npm install

First experiences with node.js/npm. From the npm-install docs I read:
npm install takes 3 exclusive, optional flags which save or update the package version in your main package.json:
--save: Package will appear in your dependencies.
--save-dev: Package will appear in your devDependencies.
--save-optional: Package will appear in your optionalDependencies.
But I can't understand how it works in practice. If, for example, I run the command:
npm install bower --save-dev
I'd expect to find a package.json file in the current directory with devDependencies set to the installed version of bower, instead I find nothing.
Am I doing/expecting something wrong?
Using node v0.10.21, npm 1.3.12 on Ubuntu 12.04 x64
npm won't create package.json for you, but it will create the necessary dependencies for you as long as package.json exists and is legal JSON.
Create it like so
echo {} > package.json
Then, doing npm i --save whatever will add whatever#~x.x.x as a dependency as expected. The file needs to be there, and be JSON, that's it.
npm install only fetches the packages from the registry and puts them in your ./node_modules. It updates your package.json to register this new dependency if you tell it to.
Your package.json has three dependency blocks :
dependencies - these are needed for your app to run.
devDependencies - these are needed for the developer environments for your app (this is how your teammates can get the packages that you recently added to the project. The dependencies listed here are not required on production hosts.)
optionalDependencies - These packages are optional and it is OK if npm cant reolve the package to install. i.e a build failure does not cause npm install to fail (Note however, that your app should handle cases where the package cannot be found.)
Here is the behavior with the different usages of the npm install command:
$ npm install async #Only installs, no change made to package.json
$ npm install async --save #Installs, adds async#version to dependencies block
$ npm install async --save-dev # Installs, adds async#version to the devDependencies block
$ npm install async --save-optional # Installs, adds async#version to the optionalDependencies block

npm installs all modules in /usr/local/lib/node_modules/

I have node.js 0.8.14 installed on Ubuntu 12.10. I created a directory in my home directory with a sub directory node_modules. I want to install some local node modules there but running
npm install myModule
in this directory installs this module in /usr/local/lib/node_modules/ (same behavior as installing the module with the -g flag
There is no node path in .bashrc.
Any idea how I can install local node modules?
After some further research I found the solution.
Running the command npm config ls revealed that the default config global=false (you see the default config with npm config ls -l) was overwritten by global=true in /home/vsdev/.npmrc and /usr/local/etc/npmrc.
Reverting this to global=false solved the issue.
That is odd.
FYI you don't need to create the node_modules directory, npm will do that for you
npm normally just installs to the current directory. Even if the package you are installing is configured to prefer global installation, npm will install it locally unless you explicitly pass the -g parameter.
can you run the following shell commands and confirm npm is really the real npm?
which npm
alias | grep npm
npm install load all in node_modules then it might be version 3 behaviour http://blog.npmjs.org/post/110924823920/npm-weekly-5 or as mentioned by #vsdev so once you make sure it version 3 behaviour and u want to go with it then its fine else follow below
1- uninstall all modules.. into the node_modules folder in your project then execute: npm uninstall *
2- Tell npm to install with legacy bundling for this one install:
npm install --legacy-bundling
A "permanent" alternative:
Set your npm config to always use legacy bundling...
npm set legacy-bundling=true
.. and run as usual:
npm install
*fetching dependencies with legacy bundling will take a lot more time because many several different versions of the same dependencies will be installed.

How do you prevent install of "devDependencies" NPM modules for Node.js (package.json)?

I have this in my package.json file (shortened version):
{
"name": "a-module",
"version": "0.0.1",
"dependencies": {
"coffee-script": ">= 1.1.3"
},
"devDependencies": {
"stylus": ">= 0.17.0"
}
}
I am using NPM version 1.1.1 on Mac 10.6.8.
When I run the following command from the project root, it installs both the dependencies and devDependencies:
npm install
I was under the impression that this command installed the devDependencies:
npm install --dev
How do I make it so npm install only installs dependencies (so production environment only gets those modules), while something like npm install --dev installs both dependencies and devDependencies?
The npm install command will install the devDependencies along other dependencies when run inside a package directory, in a development environment (the default).
In version 8.x and above use --omit=dev flag to install only regular dependencies:
npm install --omit=dev
This will install only dependencies, and not devDependencies, regardless of the value of the NODE_ENV environment variable.
If you use 6.x or an earlier version, you need to use the --only=prod flag instead.
Note:
Before v3.3.0 of npm (2015-08-13), the option was called --production, i.e.
npm install --production
You may also need --no-optional flag.
I run into that problem too! npm install is somewhat confusing and web posts keep bringing in the -d/--dev flags as if there is an explicit 'development' install mode.
npm install will install both "dependencies" and "devDependencies"
npm install --production will only install "dependencies"
npm install --dev will only install "devDependencies"
The new option is:
npm install --only=prod
If you want to install only devDependencies:
npm install --only=dev
If you have already installed all your dependencies, and you want to avoid having to download your production packages from NPM again, you can simply type:
npm prune --production
This will remove your dev dependencies from your node_modules folder, which is helpful if you're trying to automate a two step process like
Webpack my project, using dev dependencies
Build a Docker image using only production modules
Running npm prune in between will save you from having to reinstall everything!
If you read this POST in 2016, please achieve what you want by using
--only={prod[uction]|dev[elopment]}
argument will cause either only devDependencies or only non-devDependencies to be installed regardless of the NODE_ENV.
from: https://docs.npmjs.com/cli/install
When using "npm install" the modules are loaded and available throughout your application regardless of if they are "devDependencies" or "dependencies". Sum of this idea: everything which your package.json defines as a dependency (any type) gets installed to node_modules.
The purpose for the difference between dependencies/devDependencies/optionalDependencies is what consumers of your code can do w/ npm to install these resources.
Per the documentation: https://npmjs.org/doc/json.html...
If someone is planning on downloading and using your module in their
program, then they probably don't want or need to download and build
the external test or documentation framework that you use.
In this case, it's best to list these additional items in a
devDependencies hash.
These things will be installed whenever the --dev configuration flag
is set. This flag is set automatically when doing npm link or when
doing npm install from the root of a package, and can be managed like
any other npm configuration param. See config(1) for more on the
topic.
However, to resolve this question, if you want to ONLY install the "dependencies" using npm, the following command is:
npm install --production
This can be confirmed by looking at the Git commit which added this filter (along with some other filters [listed below] to provide this functionality).
Alternative filters which can be used by npm:
--save => updates dependencies entries in the {{{json}}} file
--force => force fetching remote entries if they exist on disk
--force-latest => force latest version on conflict
--production => do NOT install project devDependencies
--no-color => do not print colors
#dmarr try using npm install --production
npm will install dev dependencies when installing from inside a package (if there is a package.json in the current directory). If it is from another location (npm registry, git repo, different location on the filesystem) it only installs the dependencies.
I suggest to use npm ci. If you want to install only production-needed packages (as you wrote - without devDependencies) then:
npm ci --only=production
or
NODE_ENV=production npm ci
If you prefer oldschool npm install then:
npm install --production
or
NODE_ENV=production npm install
Here is good answer why you should use npm ci.
It's worth mentioning that you can use the NODE_ENV environment variable to achieve the same result. Particularly useful if you're containerizing your Node application (e.g. Docker).
NODE_ENV=production npm install
The above code will install all your dependencies but the dev ones (i.e. devDependencies).
if you need to use environment variables in your Dockerfile more information can be found here.
Environment variables are easy to overwrite whenever needed (e.g. if you want to run your test suite say on Travis CI). If that were the case you could do something like this:
docker run -v $(pwd):/usr/src/app --rm -it -e NODE_ENV=production node:8 npm install
NPM Documentation here
production
Default: false
Type: Boolean
Set to true to run in "production" mode.
devDependencies are not installed at the topmost level when running local npm install without any arguments.
Set the NODE_ENV="production" for lifecycle scripts.
Happy containerization =)
npm install --production --no-optional
It installs only deps from dependencies and will ignore optionalDependencies and devDependencies
Use npm install packageName --save this will add package in dependencies, if you use npm install packageName --save-dev then it devDependencies.
npm install packageName --save-dev should be used for adding packages for development purpose. Like adding TDD packages (Chai, mocha, etc). Which are used in development and not in production.
I have found that, when trying to install dev dependencies for a package that contains a node addon, you cannot avoid building the addon when running npm install --dev even if you just want to install the devDependencies. So, I had to go around npm's back:
node -e 'console.log( Object.keys( require( "./package.json" ).devDependencies ) );' | \
sed -e "s/^[^']*'//" -e "s/'.*$//" | \
xargs npm install
Or, better (and more succinctly) yet,
node -e 'Object.keys( require( "./package.json" ).devDependencies )
.map( function( item ){ console.log( item ) } );' | xargs npm install
I ran into a problem in the docker node:current-slim (running npm 7.0.9) where npm install appeared to ignore --production, --only=prod and --only=production. I found two work-arounds:
use ci instead (RUN npm ci --only=production) which requires an up-to-date package-lock.json
before npm install, brutally edit the package.json with:
RUN node -e 'const fs = require("fs"); const pkg = JSON.parse(fs.readFileSync("./package.json", "utf-8")); delete pkg.devDependencies; fs.writeFileSync("./package.json", JSON.stringify(pkg), "utf-8");'
This won't edit your working package.json, just the one copied to the docker container.
Of course, this shouldn't be necessary, but if it is (as it was for me), there's your hack.
Need to add to chosen answer: As of now, npm install in a package directory (containing package.json) will install devDependencies, whereas npm install -g will not install them.
npm install --production is the right way of installing node modules which are required for production. Check the documentation for more details
Now there is a problem, if you have package-lock.json with npm 5+. You have to remove it before use of npm install --production.

Resources