451

Is package.json supposed to be manually edited? Couldn't a program like npm just look through the files, see the "require" statements, and then use that to put the necessary entries in the package.json file? Are there any programs like that?

neuromancer
  • 53,769
  • 78
  • 166
  • 223
  • 2
    until now, i edited the file by hand: adding every package (and min. version) i need. then run `npm link` – Philipp Kyeck Apr 01 '12 at 08:18
  • 2
    https://npmjs.org/doc/install.html, this can also be used to automatically update the package.json while installing a new package – V31 Feb 06 '14 at 07:50
  • 1
    @neromancer, put down your Gibson books and fix this! :) – prasanthv May 13 '14 at 04:10
  • 1
    https://www.npmjs.com/package/npm-collect does exactly this and more – coderofsalvation Nov 05 '15 at 09:50
  • 2
    I love how nobody answered this question correctly except for one answer that was then deleted after an admin review. OP wants to know what will automatically install/save dependencies based on import/require statements in their code. The NPM package "auto-install" is the answer that OP was looking for. – Matt Diamond Dec 08 '17 at 18:31
  • Perhaps you OP can help. I need to create a package.json file from my home directory, not a project. The package.json needs to contain all of the packages found within the GLOBAL and the node_modules directories that are in my HOME directory. The npm init does NOT do what I'm looking for. Do you know if this is possible? – edjm Oct 08 '20 at 20:15

12 Answers12

628

The package.json file is used by npm to learn about your node.js project.

Use npm init to generate package.json files for you!

It comes bundled with npm. Read its documentation here: https://docs.npmjs.com/cli/init

Also, there's an official tool you can use to generate this file programmatically: https://github.com/npm/init-package-json

Ore4444
  • 9,119
  • 2
  • 23
  • 29
  • 9
    Thanks `npm init` was just what I was looking for! Also after that I usually run `npm shrinkwrap` to create a `npm-shrinkwrap.json` file – Jasdeep Khalsa Mar 22 '13 at 23:47
  • 77
    Per `npm init`: Use `npm install --save` afterwards to install a package and save it as a dependency in the package.json file. – Brad Koch May 25 '13 at 23:40
  • 5
    After running `npm init` in the Package Manager Console from Visual Studio 2015, it just displays `[...] Press ^C at any time to quit.` and stops without asking anything or creating the json file. Am I missing something? – Michael Hilus Sep 04 '15 at 09:46
  • Yes, please do :) It would mean the world to me – Ore4444 Sep 24 '15 at 12:58
  • 2
    npmjs.com/package/npm-collect allows you to collect any already installed modules – coderofsalvation Nov 05 '15 at 09:54
  • do we run `npm init` for every 'web app' (web site) that we create?? ... or do we just run `npm init` once after we install nodejs on our computer?? – dsdsdsdsd Mar 11 '16 at 15:18
  • commenting to say this is awesome and shoudl be marked correct – swyx Nov 28 '16 at 07:20
  • this doesn't seem to correctly generate dependencies for packages that are not public github repositories – Michael Jan 12 '17 at 23:15
  • @dsdsdsdsd You will want to run this for every app. This is what builds the package for that specific app. For example, one app you have may need to use ws, but another one won't. As such, you want a separate init file for each one. Keep in mind you will definitely want these to be in separate directories as well. – S. Buda Mar 13 '17 at 15:57
  • 4
    `npm init --force --yes` is the one liner to have this file generated – Bernhard Döbler Jun 16 '17 at 17:11
211

First off, run

npm init

...will ask you a few questions (read this first) about your project/package and then generate a package.json file for you.

Then, once you have a package.json file, use

npm install <pkg> --save

or

npm install <pkg> --save-dev

...to install a dependency and automatically append it to your package.json's dependencies list.

(Note: You may need to manually tweak the version ranges for your dependencies.)

Andre Bulatov
  • 1,090
  • 3
  • 16
  • 47
nzondlo
  • 4,166
  • 4
  • 18
  • 20
191

I just wrote a simple script to collect the dependencies in ./node_modules. It fulfills my requirement at the moment. This may help some others, I post it here.

var fs = require("fs");

function main() {
  fs.readdir("./node_modules", function (err, dirs) {
    if (err) {
      console.log(err);
      return;
    }
    dirs.forEach(function(dir){
      if (dir.indexOf(".") !== 0) {
        var packageJsonFile = "./node_modules/" + dir + "/package.json";
        if (fs.existsSync(packageJsonFile)) {
          fs.readFile(packageJsonFile, function (err, data) {
            if (err) {
              console.log(err);
            }
            else {
              var json = JSON.parse(data);
              console.log('"'+json.name+'": "' + json.version + '",');
            }
          });
        }
      }
    });

  });
}

main();

In my case, the above script outputs:

"colors": "0.6.0-1",
"commander": "1.0.5",
"htmlparser": "1.7.6",
"optimist": "0.3.5",
"progress": "0.1.0",
"request": "2.11.4",
"soupselect": "0.2.0",   // Remember: remove the comma character in the last line.

Now, you can copy&paste them. Have fun!

douyw
  • 4,034
  • 1
  • 30
  • 28
  • 45
    you should publish this as an npm module – Ben Mar 26 '13 at 07:59
  • now what do you do when you get 770 lines back..? I only have 58 in package.json including devDependencies :-/ – Sherzod Mar 27 '16 at 17:35
  • 5
    Note that built-in [`npm ls --depth=0`](http://stackoverflow.com/a/16704412/245966) will print more or less the same (not sure if it was the case in 2012 though) – jakub.g May 16 '16 at 18:51
  • 6
    This is not a correct way to handle this. This will output every dependency in every module. So if your package needs package `a`, and package `a` needs packages `b` and `c`, this script will output all levels, so `a`, `b`, `c` which is **not** correct. It should only output `a`, the sub-packages will be automatically resolved. – Sallar Apr 02 '17 at 13:25
  • Is it me, or does it seem most answers are assuming that you are not starting from an existing system where the node_modules were copied or built by hand? There are times when I am handed a project folder, with private modules in it and I do not have access to the repository. I still want to automate recreating the project once I put modules in MY repository. Or perhaps I am told to 'just copy this node_modules folder'. yes, yes, best practices, but I deal with the reality of devs who might not know what they are doing. This helps me begin to straighten out such a project. Thanks for sharing! – noelhx Jun 28 '17 at 13:23
  • What kind of script is this and how would I run it? – Demodave Jul 19 '17 at 20:13
  • @Demodave in case this is helpful to future readers: this is JavaScript. Install Node.js, save the script as dep.js, then run "node dep.js" in the folder containing node_modules/. – jarmod Jun 27 '18 at 18:22
91

npm init

to create the package.json file and then you use

ls node_modules/ | xargs npm install --save

to fill in the modules you have in the node_modules folder.

Edit: @paldepind pointed out that the second command is redundant because npm init now automatically adds what you have in your node_modules/ folder. I don't know if this has always been the case, but now at least, it works without the second command.

Pylinux
  • 11,278
  • 4
  • 60
  • 67
  • 5
    This is extremely helpful if you wasn't using the --save for every module you installed. –  Jan 17 '14 at 16:10
  • 7
    I found that `npm init` had automatically added dependencies based on installed packages and that there was no need to run the second command. – paldepind Feb 12 '14 at 12:35
  • I'm so glad that you can depend on the node_modules folder names in this manner... phew! – DT Rush May 10 '15 at 07:42
  • This is also fantastically useful when using `npm dedupe`, which pulls dependencies that are shared among your modules out of those modules and stores them at the top level of your `node_modules` directory. But it doesn't touch `package.json`! With this, you can commit and share your deduplicated setup. – Pathogen Jun 12 '15 at 15:41
  • 1
    Great answer for anyone adding package.json after the fact. – Carrie Kendall Nov 02 '15 at 21:58
  • Very nice and short answer!! But why isn't this the accepted answer? – Frederik.L Dec 14 '15 at 05:46
  • 'xargs' is not recognized as the name of a cmdlet – Demodave Jul 19 '17 at 20:13
  • @Demodave `xargs` is a *nix tool, so since you're on windows you need to either run the command in cygwin or git_bash, but as I also write in the answer it should be enough for you to just write `npm init` and it should auto fill the `package.json` file. – Pylinux Jul 21 '17 at 05:35
25

Command line:

npm init

will create package.json file

To install , update and uninstall packages under dependencies into package.json file:

Command line :

npm install <pkg>@* --save 

will automatically add the latest version for the package under dependencies into package.json file

EX:

npm install node-markdown@* --save

Command line:

npm install <pkg> --save

also will automatically add the latest version for the package under dependencies into package.json file

if you need specific version for a package use this Command line:

npm install <pkg>@<version> --save

will automatically add specific version of package under dependencies into package.json file

EX:

npm install koa-views@1.0.0 --save

if you need specific range of version for a package use this Command line:

npm install <pkg>@<version range>

will automatically add the latest version for the package between range of version under dependencies into package.json file

EX:

npm install koa-views@">1.0.0 <1.2.0" --save

For more details about how to write version for package npm Doc

Command line:

npm update --save

will update packages into package.json file and will automatically add updated version for all packages under dependencies into package.json file

Command line:

npm uninstall <pkg> --save

will automatically remove package from dependencies into package.json file and remove package from node_module folder

ahmed hamdy
  • 5,096
  • 1
  • 47
  • 58
16

Running npm init -y makes your package.json with all the defaults.
You can then change package.json accordingly
This saves time many a times by preventing pressing enter on every command in npm init

Abhinav Singi
  • 3,379
  • 1
  • 20
  • 27
6

You can now use Yeoman - Modern Web App Scaffolding Tool on node terminal using 3 easy steps.

First, you'll need to install yo and other required tools:

$ npm install -g yo bower grunt-cli gulp

To scaffold a web application, install the generator-webapp generator:

$ npm install -g generator-webapp  // create scaffolding 

Run yo and... you are all done:

$ yo webapp  // create scaffolding 

Yeoman can write boilerplate code for your entire web application or Controllers and Models. It can fire up a live-preview web server for edits and compile; not just that you can also run your unit tests, minimize and concatenate your code, optimize images, and more...

Yeoman (yo) - scaffolding tool that offers an ecosystem of framework-specific scaffolds, called generators, that can be used to perform some of the tedious tasks mentioned earlier.

Grunt / gulp - used to build, preview, and test your project.

Bower - is used for dependency management, so that you no longer have to manually download your front-end libraries.

Adesh M
  • 436
  • 5
  • 10
5

Based on Pylinux's answer, below is a solution for Windows OS,

dir node_modules > abc.txt
FOR /F %k in (abc.txt) DO npm install --save

Hope it helps.

Anmol Saraf
  • 15,075
  • 10
  • 50
  • 60
  • Either, you can just type npm install at top of abc.txt and at the bottom --save with remove new link will work even. – Ronak Amlani Jun 28 '17 at 07:23
  • Note that, while helpful, this may install the wrong versions of the NPM packages, which may cause the app to fail. – jarmod Jun 27 '18 at 18:24
  • with PowerShell it gets a little simple than that: ls .\node_modules\ | Select-Object Name | ForEach-Object { npm install --save } – Peter M. Jun 03 '21 at 08:49
2

use command npm init -f to generate package.json file and after that use --save after each command so that each module will automatically get updated inside your package.json for ex: npm install express --save

2

1. Choice

If you git and GitHub user:

    generate-package more simply, than npm init.

else

and/or you don't like package.json template, that generate-package or npm init generate:

    you can generate your own template via scaffolding apps as generate, sails or yeoman.


2. Relevance

This answer is relevant for March 2018. In the future, the data from this answer may be obsolete.

Author of this answer personally used generate-package at March 2018.


3. Limitations

You need use git and GitHub for using generate-package.


4. Demonstration

For example, I create blank folder sasha-npm-init-vs-generate-package.

4.1. generate-package

Command:

D:\SashaDemoRepositories\sasha-npm-init-vs-generate-package>gen package
[16:58:52] starting generate
[16:59:01] √ running tasks: [ 'package' ]
[16:59:04] starting package
? Project description? generate-package demo
? Author's name? Sasha Chernykh
? Author's URL? https://vk.com/hair_in_the_wind
[17:00:19] finished package √ 1m

package.json:

{
  "name": "sasha-npm-init-vs-generate-package",
  "description": "generate-package demo",
  "version": "0.1.0",
  "homepage": "https://github.com/Kristinita/sasha-npm-init-vs-generate-package",
  "author": "Sasha Chernykh (https://vk.com/hair_in_the_wind)",
  "repository": "Kristinita/sasha-npm-init-vs-generate-package",
  "bugs": {
    "url": "https://github.com/Kristinita/sasha-npm-init-vs-generate-package/issues"
  },
  "license": "MIT",
  "engines": {
    "node": ">=4"
  },
  "scripts": {
    "test": "mocha"
  },
  "keywords": [
    "generate",
    "init",
    "npm",
    "package",
    "sasha",
    "vs"
  ]
}

4.2. npm init

D:\SashaDemoRepositories\sasha-npm-init-vs-generate-package>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: (sasha-npm-init-vs-generate-package)
version: (1.0.0) 0.1.0
description: npm init demo
entry point: (index.js)
test command: mocha
git repository: https://github.com/Kristinita/sasha-npm-init-vs-generate-package
keywords: generate, package, npm, package, sasha, vs
author: Sasha Chernykh
license: (ISC) MIT
About to write to D:\SashaDemoRepositories\sasha-npm-init-vs-generate-package\package.json:

{
  "name": "sasha-npm-init-vs-generate-package",
  "version": "0.1.0",
  "description": "npm init demo",
  "main": "index.js",
  "scripts": {
    "test": "mocha"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/Kristinita/sasha-npm-init-vs-generate-package.git"
  },
  "keywords": [
    "generate",
    "package",
    "npm",
    "package",
    "sasha",
    "vs"
  ],
  "author": "Sasha Chernykh",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/Kristinita/sasha-npm-init-vs-generate-package/issues"
  },
  "homepage": "https://github.com/Kristinita/sasha-npm-init-vs-generate-package#readme"
}


Is this ok? (yes) y
{
  "name": "sasha-npm-init-vs-generate-package",
  "version": "0.1.0",
  "description": "npm init demo",
  "main": "index.js",
  "scripts": {
    "test": "mocha"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/Kristinita/sasha-npm-init-vs-generate-package.git"
  },
  "keywords": [
    "generate",
    "package",
    "npm",
    "package",
    "sasha",
    "vs"
  ],
  "author": "Sasha Chernykh",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/Kristinita/sasha-npm-init-vs-generate-package/issues"
  },
  "homepage": "https://github.com/Kristinita/sasha-npm-init-vs-generate-package#readme"
}

I think, that generate-package more simply, that npm init.


5. Customizing

That create your own package.json template, see generate and yeoman examples.

Саша Черных
  • 2,561
  • 4
  • 25
  • 71
0

No, it isn't.

Yes, it could.

Yes, there are.

Sometimes when you comment out code or try to experiment trying out new modules, the experiement doesn't work out. Then, you have extra junk in the package.json. The follow process cleans it out, resulting in a clean list of what you're actually using and a clean node_modules folder.

[Linux] Rebuild package.json Dependencies from project

Installation

  1. [Terminal] Install auto installer: sudo npm install -g auto-install

Usage

  1. [IDE] Comment out / delete your failed experiments inside your js files
  2. [Terminal] Go to project folder: cd <project folder>
  3. [Terminal] Remove node modules: rm -rf node_modules
  4. [Terminal] Run auto installer: auto-install. Pay attention to errors.
  5. [Terminal] Terminate the watcher: CTRL+C
  6. [Terminal] Fix vulnerabilities: npm audit fix --force
  7. [Terminal] Fix errors from auto-install
  8. [Terminal] If there were errors, go back to "Run auto installer" step

Automation

  1. [VS Code][keybindings.json] Add a keyboard shortcut to the array of key bindings:
    {
    "key": "ctrl+alt+a",
    "command": "workbench.action.terminal.sendSequence",
    "args": {
    "text": "auto-install\u000D"
    }
    },
    

Caveats

  1. I guess auto-install was pre-async/await. If a file contains these, it will fail to parse that js file and it will then auto-remove any dependencies which are only referenced in that file. You can add
    var autoInstallKeep = {
    foo: require('foo')
    }
    
    to prevent module foo from auto-uninstalling due to a parse error
toddmo
  • 20,682
  • 14
  • 97
  • 107
-1
npm add <package-name>

The above command will add the package to the node modules and update the package.json file

Dileep TP
  • 135
  • 4
  • 17