Detect the indentation of code

npm install detect-indent
98 downloads in the last day
561 downloads in the last week
1 214 downloads in the last month

detect-indent Build Status

Detect the indentation of code

Pass in a string and get the indentation. Works in Node.js and the browser on any kind of text.

Use cases

  • Persisting the indentation when modifying a file.
  • Setting the right indentation in your editor.


Download the library manually or with a package-manager.


npm install --save detect-indent


bower install --save detect-indent


component install sindresorhus/detect-indent


Accepts a string and returns the indentation or null if it can't be detected.


Modify a JSON file while persisting the indentation in Node.js.

var fs = require('fs');
var detectIndent = require('detect-indent');
    "ilove": "pizza"
var file = fs.readFileSync('foo.json', 'utf8');
// tries to detect the indentation and falls back to a default if it can't
var indent = detectIndent(file) || '    ';
var json = JSON.parse(file);

json.ilove = 'unicorns';

fs.writeFileSync('foo.json', JSON.stringify(json, null, indent));
    "ilove": "unicorns"


MIT License • © Sindre Sorhus

npm loves you