Extract code comments from string or from a glob of files.
Heads up! As of v0.7.0 this no longer has a .fromFile()
method to read from the file system. See [extracting from files].
Can be used with code-context to match comments up with related code.
Install with npm
npm i extract-comments --save
Usage
var extract = require('extract-comments');
extract(string);
Example
var str = '/**\n * this is\n *\n * a comment\n*/\nvar foo = "bar";\n';
extract(str);
Results in:
{ '1':
{ begin: 1,
end: 5,
codeStart: 7 } }
content: 'this is\n\na comment\n',
blocks: [
'this is',
'a comment\n'
],
after: 'var foo = "bar";',
(The reason the key is the starting line number is that it's easy to use this format with templates)
Customize output
var context = require('code-context');
var comments = extract(str, function(comment) {
comment.context = context(comment.after);
return comment;
});
Results in:
{ begin: 1,
content: 'this is\n\na comment\n',
after: 'var foo = "bar";',
end: 5,
codeStart: 7,
blocks: [ 'this is', 'a comment\n' ],
context:
[ { begin: 1,
type: 'declaration',
name: 'foo',
value: '"bar"',
string: 'foo',
original: 'var foo = "bar";' } ] }
Prior to v0.7.0, there was a method to extract code comments from files. Here is the equivalent code to accomplish the same thing:
var fs = require('fs');
var extract = require('extract-comments');
var mapFiles = require('map-files');
function extractComments(patterns, opts) {
opts = opts || {};
opts.name = opts.rename || function(fp) {
return fp;
};
opts.read = opts.read || function(fp, options) {
var code = fs.readFileSync(fp, 'utf8');
return extract(code, options);
};
return mapFiles(patterns, opts);
}
Related
- parse-comments: Parse code comments from JavaScript or any language that uses the same format.
- code-context: Parse a string of javascript to determine the context for functions, variables and comments based on the code that follows.
- esprima-extract-comments: Extract code comments from string or from a glob of files using esprima.
Contributing
Pull requests and stars are always welcome. For bugs and feature requests, please create an issue
Run tests
Install dev dependencies.
npm i -d && npm test
Author
Jon Schlinkert
License
Copyright (c) 2014-2015 Jon Schlinkert
Released under the MIT license
This file was generated by verb-cli on March 12, 2015.