1// initialize a package.json file 2 3module.exports = init 4 5var path = require('path') 6var log = require('npmlog') 7var npa = require('npm-package-arg') 8var npm = require('./npm.js') 9var npx = require('libnpx') 10var initJson = require('init-package-json') 11var isRegistry = require('./utils/is-registry.js') 12var output = require('./utils/output.js') 13var noProgressTillDone = require('./utils/no-progress-while-running').tillDone 14var usage = require('./utils/usage') 15 16init.usage = usage( 17 'init', 18 '\nnpm init [--force|-f|--yes|-y|--scope]' + 19 '\nnpm init <@scope> (same as `npx <@scope>/create`)' + 20 '\nnpm init [<@scope>/]<name> (same as `npx [<@scope>/]create-<name>`)' 21) 22 23function init (args, cb) { 24 if (args.length) { 25 var NPM_PATH = path.resolve(__dirname, '../bin/npm-cli.js') 26 var initerName = args[0] 27 var packageName = initerName 28 if (/^@[^/]+$/.test(initerName)) { 29 packageName = initerName + '/create' 30 } else { 31 var req = npa(initerName) 32 if (req.type === 'git' && req.hosted) { 33 var { user, project } = req.hosted 34 packageName = initerName 35 .replace(user + '/' + project, user + '/create-' + project) 36 } else if (isRegistry(req)) { 37 packageName = req.name.replace(/^(@[^/]+\/)?/, '$1create-') 38 if (req.rawSpec) { 39 packageName += '@' + req.rawSpec 40 } 41 } else { 42 var err = new Error( 43 'Unrecognized initializer: ' + initerName + 44 '\nFor more package binary executing power check out `npx`:' + 45 '\nhttps://www.npmjs.com/package/npx' 46 ) 47 err.code = 'EUNSUPPORTED' 48 throw err 49 } 50 } 51 var npxArgs = [process.argv0, '[fake arg]', '--always-spawn', packageName, ...process.argv.slice(4)] 52 var parsed = npx.parseArgs(npxArgs, NPM_PATH) 53 54 return npx(parsed) 55 .then(() => cb()) 56 .catch(cb) 57 } 58 var dir = process.cwd() 59 log.pause() 60 var initFile = npm.config.get('init-module') 61 if (!initJson.yes(npm.config)) { 62 output([ 63 'This utility will walk you through creating a package.json file.', 64 'It only covers the most common items, and tries to guess sensible defaults.', 65 '', 66 'See `npm help init` for definitive documentation on these fields', 67 'and exactly what they do.', 68 '', 69 'Use `npm install <pkg>` afterwards to install a package and', 70 'save it as a dependency in the package.json file.', 71 '', 72 'Press ^C at any time to quit.' 73 ].join('\n')) 74 } 75 initJson(dir, initFile, npm.config, noProgressTillDone(function (er, data) { 76 log.resume() 77 log.silly('package data', data) 78 if (er && er.message === 'canceled') { 79 log.warn('init', 'canceled') 80 return cb(null, data) 81 } 82 log.info('init', 'written successfully') 83 cb(er, data) 84 })) 85} 86