Parse text columns, like the output of Unix commands
npm install parse-columns$ df -kP
Filesystem 1024-blocks Used Available Capacity Mounted on
/dev/disk1 487350400 467871060 19223340 97% /
devfs 185 185 0 100% /dev
map -hosts 0 0 0 100% /net
import {promisify} from 'node:util';
import childProcess from 'node:child_process';
import parseColumns from 'parse-columns';
const execFileP = promisify(childProcess.execFile);
const {stdout} = await execFileP('df', ['-kP']);
console.log(parseColumns(stdout, {
transform: (item, header, columnIndex) => {
// Coerce elements in column index 1 to 3 to a number
if (columnIndex >= 1 && columnIndex <= 3) {
return Number(item);
}
return item;
}
}));
/*
[
{
Filesystem: '/dev/disk1',
'1024-blocks': 487350400,
Used: 467528020,
Available: 19566380,
Capacity: '96%',
'Mounted on': '/'
},
…
]
*/Type: string
The text columns to parse.
Type: object
Type: string | RegExp
Default: ' '
Separator to split columns on.
string: Single character separator (default behavior)RegExp: Regular expression pattern for flexible matching
// Default space separator
parseColumns(data);
// Tab separator
parseColumns(data, {separator: '\t'});
// Any whitespace (spaces, tabs, etc.)
parseColumns(data, {separator: /\s+/});
// Either spaces or tabs
parseColumns(data, {separator: /[ \t]/});Type: string[]
Headers to use instead of the existing ones.
Type: Function
Transform elements.
Useful for being able to cleanup or change the type of elements.
The supplied function gets the following arguments and is expected to return the element:
element(string)header(string)columnIndex(number)rowIndex(number)
Fixed-width parsing needs every row to line up with the header's column boundaries.
A cell that is wider than its column cannot be detected. It has the same shape as two merged columns, or as a value that contains the separator, which this module supports on purpose. When it happens, the columns merge and the resulting keys are wrong. The module does not throw and does not warn.
Pass headers when you can. A row that produces an empty field is then a clear sign of the problem. Better still, make the command pad its own output (ps without truncation, df -P), or run it through column -t first.
- parse-columns-cli - CLI for this module