Skip to content

Commit

Permalink
line count example
Browse files Browse the repository at this point in the history
  • Loading branch information
James Halliday committed May 15, 2011
1 parent 4166bbf commit 4ca06b8
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 2 deletions.
57 changes: 55 additions & 2 deletions README.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,13 @@ divide.js:
5

$ ./divide.js -x 4.91 -z 2.51
Usage: ./divide.js -x [num] -y [num]
Missing arguments: y
Usage: node ./examples/divide.js -x [num] -y [num]

-x [required]

-y [required]

Missing required arguments: y

EVEN MORE HOLY COW
------------------
Expand Down Expand Up @@ -158,6 +163,7 @@ boolean_single.js
console.dir(argv);

***

$ ./boolean_single.js -v foo bar baz
true
[ 'bar', 'baz', 'foo' ]
Expand All @@ -173,10 +179,57 @@ boolean_double.js
console.dir(argv._);

***

$ ./boolean_double.js -x -z one two three
[ true, false, true ]
[ 'one', 'two', 'three' ]

Optimist is here to help...
---------------------------

You can describe parameters for help messages and set aliases. Optimist figures
out how to format a handy help string automatically.

line_count.js

#!/usr/bin/env node
var argv = require('optimist')
.usage('Count the lines in a file.\nUsage: $0')
.demand('f')
.alias('f', 'file')
.describe('f', 'Load a file')
.argv
;

var fs = require('fs');
var s = fs.createReadStream(argv.file);

var lines = 0;
s.on('data', function (buf) {
lines += buf.toString().match(/\n/g).length;
});

s.on('end', function () {
console.log(lines);
});

***

$ node line_count.js
Count the lines in a file.
Usage: node ./line_count.js

-f, --file [required]
Load a file

Missing required arguments: f

$ node line_count.js --file line_count.js
20

$ node line_count.js -f line_count.js
20

notes
=====

Expand Down
20 changes: 20 additions & 0 deletions examples/line_count.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#!/usr/bin/env node
var argv = require('optimist')
.usage('Count the lines in a file.\nUsage: $0')
.demand('f')
.alias('f', 'file')
.describe('f', 'Load a file')
.argv
;

var fs = require('fs');
var s = fs.createReadStream(argv.file);

var lines = 0;
s.on('data', function (buf) {
lines += buf.toString().match(/\n/g).length;
});

s.on('end', function () {
console.log(lines);
});

0 comments on commit 4ca06b8

Please sign in to comment.