代码如下:
// [Example]
// {
// "name": "npm-init",
// "version": "0.0.0",
// "description": "This is npm-init",
// "main": "index.js",
// "author": "haiyang2014"
// }
/* jshint browser: false */
'use strict';
var fs = require('fs');
var path = require('path');
var readline = require('readline');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
var pkg;
var ctx;
var pkgjson_src = path.resolve(__dirname, 'package.json');
var basename = path.basename(path.dirname(pkgjson_src));
var pkgjson = [
'name', basename,
'version', '0.0.0',
'description', 'This is ' + basename,
'main', 'index.js',
// 'test', 'echo "Error: no test specified" && exit 1',
// 'repository', 'git|http://github.com/' + basename,
// 'keywords', 'javascript|node',
// 'license', 'ISC',
'author', 'haiyang2014'
];
var pkgdata = {};
for (var i = 0, len = pkgjson.length; i < len; i += 2) {
pkgdata[pkgjson[i]] = pkgjson[i + 1];
}
function readPkgJson() {
fs.readFile(pkgjson_src, 'utf8', function (er, d) {
if (er) ctx = {};
try {
ctx = JSON.parse(d);
pkg = JSON.parse(d);
}
catch (e) {
ctx = {};
}
for (var i in ctx) {
pkgdata[i] = ctx[i];
}
console.log(ctx);
console.log([
'This utility will walk you through creating a package.json file.',
'It only covers the most common items, and tries to guess sane defaults.',
'',
'See `npm help json` for definitive documentation on these fields',
'and exactly what they do.',
'',
'Use `npm install <pkg> --save` afterwards to install a package and',
'save it as a dependency in the package.json file.',
'',
'Press ^C at any time to quit.'
].join('\n'));
promptPkgjson.index = 0;
promptPkgjson();
});
}
function promptPkgjson() {
var k = pkgjson[promptPkgjson.index],
v = pkgjson[promptPkgjson.index + 1];
rl.question(k + ': ' + (!!v ? '(' + v + ') ' : ''), function (answer) {
pkgdata[pkgjson[promptPkgjson.index]] = answer || pkgjson[promptPkgjson.index + 1];
promptPkgjson.index += 2;
if (promptPkgjson.index >= pkgjson.length) {
finishPrompt();
}
else {
promptPkgjson();
}
});
}
promptPkgjson.index = 0;
function finishPrompt() {
var d = JSON.stringify(pkgdata, null, 2) + '\n';
console.log('About to write to %s:\n\n%s\n', pkgjson_src, d);
rl.question('Is this ok? (yes)', function (ok) {
rl.close();
ok = String(ok).toLowerCase().trim();
if (ok && ok.charAt(0) !== 'y') {
console.log('Aborted.');
}
else {
fs.writeFile(pkgjson_src, d, 'utf8', function (er) {
if (er) throw er;
console.log('ok');
});
}
});
}
readPkgJson();