Chris Umbel

Natural Language Processing in node.js with "natural"

Over the last few years I've developed a bit of an interest in natural-language processing. It's never been the focus of my work, but when you're exposed to as many enterprise-class data storage/search systems as I have you have no choice but to absorb some details. Several hobby projects, sometimes involving home-brewed full-text searching, have also popped up requiring at least a cursory understanding of stemming and phonetic algorithms. Another recurring theme in my hobby projects has been classification for custom spam filtering and analyzing twitter sentiment. node.js logo

In general, accomplishing these goals simply required the use of someone else's hard work, wether it be having Solr/ Lucene to stem my corpora at the office, using the Ruby classifier gem to analyze tweets about stocks or using the Python Natural Language Toolkit for... Well, pretty much anything.

Recent months have brought a new platform into my hobby work, node.js, which, while stable, still has maturing to do. Like so many things I work with anymore the need for natural-language facilities arose and I found the pickings pretty slim. I have to be honest. That's *exactly* what I was hoping for; an opportunity to sink my teeth into the algorithms themselves.

Thus I began work on "natural", a module of natural languages algorithms for node.js. The idea is loosely based on the Python NLTK in that all algorithms are in the same package, however it will likely never be anywhere near as complete. I'd be lucky for "natural" to ever do 1/2 of what NLTK does without plenty of help. As of version 0.0.17 it has two stemmers (Porter and Lancaster), one classifier (Naive Bayes), two phonetic algorithms (Metaphone and SoundEx) and an inflector.

The strategy was to cast a wide enough net to see how the algorithms might fit together in terms of interface and dependancies first. Making them performant and perfectly accurate is step two, which admittedly will still require some work. At the time of writing "natural" is in version 0.0.17 and everything seems to work (not in an official beta of any kind) but until the version ticks 0.1.0 it's subject to significant internal change. Hopefully the interfaces will stay the same.

With the exception of the Naive Bayes classifier (to which you can supply tokens of your own stemming) all of these algorithms have no real applicability outside of English. This is a problem I'd like to rectify after solidifying a 0.1.0 release and would love to get some more people involved to accomplish it.


In order to use "natural" you have to install it... naturally. Like most node modules "natural" is packaged up in an NPM and can be install from the command line as such:

npm install natural

If you want to install from source (which can be found here on github), pull it and install the npm from the source directory.

git clone git://
cd natural
npm install .


The first class of algorithms I'd like to outline is stemming. As stated above the Lancaster and Porter algorithms are supported as of 0.0.17. Here's a basic example of stemming a word with a Porter Stemmer.

var natural = require('natural'),
    stemmer = natural.PorterStemmer;

var stem = stemmer.stem('stems');
stem = stemmer.stem('stemming');
stem = stemmer.stem('stemmed');
stem = stemmer.stem('stem');

Above I simply required-up the main "natural" module and grabbed the PorterStemmer sub-module from within. Calling the "stem" function takes an arbitrary string and returns the stem. The above code returns the following output:


For convenience stemmers can patch String with methods to simplify the process by calling the attach method. String objects will then have a stem method.

stem = 'stemming'.stem();

Generally you'd be interested in stemming an entire corpus. The attach method provides a tokenizeAndStem method to accomplish this. It breaks the owning string up into an array of strings, one for each word, and stems them all. For example:

var stems = 'stems returned'.tokenizeAndStem();

produces the output:

[ 'stem', 'return' ]

Note that the tokenizeAndStem method will omit certain words by default that are considered irrelevant (stop words) from the return array. To instruct the stemmer to not omit stop words pass a true in to tokenizeAndStem for the keepStops parameter. Consider:

console.log('i stemmed words.'.tokenizeAndStem());
console.log('i stemmed words.'.tokenizeAndStem(true));
[ 'stem', 'word' ]
[ 'i', 'stem', 'word' ]

All of the code above would also work with a Lancaster stemmer by requiring the LancasterStemmer module instead, like:

var natural = require('natural'),
    stemmer = natural.LancasterStemmer;

Of course the actual stems produced could be different depending on the algorithm chosen.


Phonetic algorithms are also provided to determine what words sound like and compare them accordingly. The old (and I mean old... like 1918 old) SoundEx and the more modern Metaphone algorithm are supported as of 0.0.17.

The following example compares the string "phonetics" and the intentional misspelling "fonetix" and determines they sound alike according to the Metaphone algorithm.

var natural = require('natural'),
    phonetic = natural.Metaphone;

var wordA = 'phonetics';
var wordB = 'fonetix';

if(, wordB))
    console.log('they sound alike!');

The raw code the phonetic algorithm produces can be retrieved with the process method:

var phoneticCode = phonetic.process('phonetics');

resulting in:


Like the stemming implementations the phonetic modules have an attach method that patches String with shortcut methods, most notably soundsLike for comparison:


    console.log('they sound alike!');

attach also patches in a phonetics and tokenizeAndPhoneticize methods to retrieve the phonetic code for a single word and an entire corpus respectively.

console.log('phonetics rock'.tokenizeAndPhoneticize());

which outputs:

[ 'FNTKS', 'RK' ]

The above could could also use SoundEx by substituting the following in for the require.

var natural = require('natural'),
    phonetic = natural.SoundEx;


Basic inflectors are in place to convert nouns between plural and singular forms and to turn integers into string counters (i.e. '1st', '2nd', '3rd', '4th 'etc.).

The following example converts the word "radius" into its plural form "radii".

var natural = require('natural'),
    nounInflector = new natural.NounInflector();

var plural = nounInflector.pluralize('radius');

Singularization follows the same pattern as is illustrated in the following example wich converts the word "beers" to its singular form, "beer".

var singular = nounInflector.singularize('beers');

Just like the stemming and phonetic modules an attach method is provided to patch String with shortcut methods.


A NounInflector instance can do custom conversion if you provide expressions via the addPlural and addSingular methods. Because these conversion aren't always symmetric (sometimes more patterns may be required to singularize forms than pluralize) there needn't be a one-to-one relationship between addPlural and addSingular calls.

nounInflector.addPlural(/(code|ware)/i, '$1z');
nounInflector.addSingular(/(code|ware)z/i, '$1');



which would result in:


Here's an example of using the CountInflector module to produce string counter for integers.

var natural = require('natural'),
    countInflector = natural.CountInflector;





At the moment classification is supported only by the Naive Bayes algorithm. There are two basic steps involved in using the classifier: training and classification.

The following example requires-up the classifier and trains it with data. The train method accepts an array of objects containing the name of the classification and the sample corpus.

var natural = require('natural'),
classifier = new natural.BayesClassifier();
classifier.addDocument("my unit-tests failed.", 'software');
classifier.addDocument("tried the program, but it was buggy.", 'software');
classifier.addDocument("the drive has a 2TB capacity.", 'hardware');
classifier.addDocument("i need a new power supply.", 'hardware');

By default the classifier will tokenize the corpus and stem it with a LancasterStemmer. You can use a PorterStemmer by passing it in to the BayesClassifier constructor as such:

var natural = require('natural'),
stemmer = natural.PorterStemmer,
classifier = new natural.BayesClassifier(stemmer);

With the classifier trained it can now classify documents via the classify method:

console.log(classifier.classify('did the tests pass?'));
console.log(classifier.classify('did you buy a new drive?'));

resulting in the output:


Similarly the classifier can be trained on arrays rather than strings, bypassing tokenization and stemming. This allows the consumer to perform custom tokenization and stemming if any at all. This is especially useful in a non-natural language scenario.

classifier.addDocument( ['unit', 'test'], 'software');
classifier.addDocument( ['bug', 'program'], 'software');
classifier.addDocument(['drive', 'capacity'], 'hardware');
classifier.addDocument(['power', 'supply'], 'hardware');


It's possible to persist and recall the results of a training via the save method:

var natural = require('natural'),
classifier = new natural.BayesClassifier();

classifier.addDocument( ['unit', 'test'], 'software');
classifier.addDocument( ['bug', 'program'], 'software');
classifier.addDocument(['drive', 'capacity'], 'hardware');
classifier.addDocument(['power', 'supply'], 'hardware');

classifier.train();'classifier.json', function(err, classifier) {
    // the classifier is saved to the classifier.json file!

The training could then be recalled later with the load method:

var natural = require('natural'),
    classifier = new natural.BayesClassifier();

natural.BayesClassifier.load('classifier.json', null, function(err, classifier) {
    console.log(classifier.classify('did the tests pass?'));


This concludes the current state of "natural". Like I said in the introduction, there are certainly potential improvements in both terms of accuracy and performance. Now that 0.0.17 has been released features are frozen while I focus on improving both for 0.1.0.

Post-0.1.0 I intend to make "natural" more complete; slowly staring to match the NLTK with additional algorithms of all classifications and hopefully for additional languages. For that I humbly ask assistance:)

Sun May 22 2011 22:29:06 GMT+0000 (UTC)

6 Comments Comment Feed - Permalink
Hi Chris, I would love to try this out but when I try and install natural I get:

Checking for library z                   : no such environment: default

I cannot see a way to install "z" as it has disaapeared fom the NPM registry.

Any ideas?
by Jake on Tue Oct 25 2011 13:37:26 GMT+0000 (UTC)
oh no! i'll take a look and see what i can do shortly.

thanks for letting me know!
by Chris Umbel on Tue Nov 01 2011 12:06:29 GMT+0000 (UTC)
as of natural 0.0.56 the dependency on the "compress" module is soft so it should install fine on windows. everything should work except the wordnet module will require you to download the data and index files yourself.
by Chris Umbel on Mon Nov 07 2011 14:00:30 GMT+0000 (UTC)
Thank you so much, Chris for your work. I liked reading you post!
by Artem on Thu Jul 10 2014 10:23:25 GMT+0000 (UTC)
I've read some just right stuff here. Certainly value bookmarking for revisiting.

I wonder how much effort you put to create any such wonderful informative website.
by red little tikes trike on Tue Mar 17 2015 19:38:25 GMT+0000 (UTC)

I have a c++ library and i would like to use yours to call and use to calculate Levenstiandistance. Could you please direct me through the steps. 
by nithin uppalapati on Thu Apr 16 2015 05:02:46 GMT+0000 (UTC)
Add a comment
E mail (Private)
Follow Chris
RSS Feed