Skip to content

Instantly share code, notes, and snippets.

@mgtitimoli
Created April 23, 2020 15:27
Show Gist options
  • Save mgtitimoli/9cfb18f15683d242873fd6d9622d0fd7 to your computer and use it in GitHub Desktop.
Save mgtitimoli/9cfb18f15683d242873fd6d9622d0fd7 to your computer and use it in GitHub Desktop.
Sort in Node.JS using OS commands
import * as childProcess from 'child_process';
import { promisify } from 'util';
type OptionalParams = {
fieldSeparator?: string;
hasHeader?: boolean;
};
type MandatoryParams = {
byColumn: number;
fromFilePath: string;
toFilePath: string;
};
type ParamsWithDefaults = Required<OptionalParams> & MandatoryParams;
type Params = OptionalParams & MandatoryParams;
const exec = promisify(childProcess.exec);
const getSortCommand = ({
byColumn,
fieldSeparator,
fromFilePath,
hasHeader,
toFilePath,
}: ParamsWithDefaults) =>
[
'sort',
`--field-separator "${fieldSeparator}"`,
`--key ${byColumn},${byColumn}`,
...(hasHeader ? [] : [fromFilePath]),
`>> ${toFilePath}`,
].join(' ');
const getTailCommand = ({ fromFilePath }: ParamsWithDefaults) =>
`tail -n +2 ${fromFilePath}`;
const getHeadCommand = ({ fromFilePath, toFilePath }: ParamsWithDefaults) =>
`head -n 1 ${fromFilePath} > ${toFilePath}`;
const getCommandWithHeader = (params: ParamsWithDefaults) =>
getHeadCommand(params) +
' && ' +
getTailCommand(params) +
' | ' +
getSortCommand(params);
const fieldSeparatorDefault = ';';
const sortCsvFile = ({
hasHeader = true,
fieldSeparator = fieldSeparatorDefault,
...rest
}: Params) =>
exec(
hasHeader
? getCommandWithHeader({ hasHeader, fieldSeparator, ...rest })
: getSortCommand({ hasHeader, fieldSeparator, ...rest }),
);
export default sortCsvFile;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment