Using the Stanford Classifier with Node.js

The Stanford Classifier is a powerful classifying library that is freely available for anyone to use. Given the right amount of data, it can be used to classify blocks of texts with good accuracy. Lets get started with using the Stanford Classifier in Node.js.

Getting Started

Install the stanford-classifier Node.js module from the npm repository. The stanford-classifier Node.js module uses Stanford Classifier v3.5.2 internally and has node-java as a dependency. Your environment should have Java properly configured to work with node-java. You can learn more about node-java configurations here. To install the stanford-classifier run the following in the terminal:

npm install stanford-classifier --save

The module will appear in the projects root node_modules directory. The Node.js module can be viewed in the npm repository


The classifier needs to be trained with pre-trained data. Without trained data, the classifier will not work as expected and will not be accurate. Regardless of which classification algorithm is being used, the classifier needs a robust dataset to yield accurate classifications. I built a small dataset that contains organization and band Twitter descriptions. The dataset can be used to train the stanford-classifier. It can be downloaded here.

Training And Classifying The Classifier

The train() method is used to train the stanford-classifier with a pre-trained dataset. Here is an example of how to use the train() method to train the stanford-classifier.

Example :

/// Dependencies
var stanfordClassifier = require('stanford-classifier');
var byline = require('byline');
var fs = require('fs');

/// Initialize the Stanford Classifier
var sc = new stanfordClassifier();

var mem = [];

/// Create a stream to read the dataset
var stream = byline(fs.createReadStream('dataset.txt', {
    encoding: 'utf8'

/// Push each line into memory
stream.on('data', function(line) {

/// Use the training dataset in memory to train the classifier dataset
stream.on('end', function() {
    for (var i = 0; i < mem.length; i++) {
        var line = mem[i];

/// Sync the classifier with the classifiers dataset
/// Use the classifier
  console.log(sc.classify('Our Twitter run by the band and crew to give you an inside look into our lives on the road'));
/// BAND

After the classifier has been trained use the syncClassifier() method to sync the trained dataset with the classifier.

Customizing The Classifier

Options can be sent directly to the classifier when initializing the stanford-classifier instance.

var sc = new stanfordClassifier(options);

The options can either be a path to a property file or an object with options. The default options are the following :

# Features
# Printing
# printClassifier=HighWeight
# Mapping
# Optimization

other options that be used are here.

NPM Repository :
Github Repository:

If you need any help, send me a tweet on twitter