Cross-platform CLI commands
I was trying to create a CLI package using my linux system, and I wanted to trigger a command that reads a file. Being linux, I used
cat and it worked perfectly. But, for people using my package on a different operating system like windows, they'd never be able to trigger a command like
This CLI package has many commands with different purposes mapped to different operating system commands. You give it a command and the required options, and it runs the appropriate command for the platform is used with the options provided.
This library comes in handy when creating a CLI package and you want to target various platforms.
npm i cross-cmd
In your project
Let's say you use
spawnSync from the child_process module in NodeJS (it could be any function, as long as it executes terminal commands) and you're developing your package on a linux system:
const spawnSync = ;
What happens here is that
cross-cmd checks its list of commands, gets the one with
cat and appropriately apply the command for the platform it is being run on. For example, your package with this command executed on linux and windows respectively would be:
# linuxcat path-to-file# windowstype path-to-file
This is because 'type' is a win32 representative associated with linux's 'cat' as saved in the list of commands.
cross-cmdis not installed globally, that's why it is accessed with
node ./node_modules...instead of
cross-cmd.... Just as I wouldn't want the users of this package to have it installed globally against their will, the users wouldn't also want the users of their packages to do the same.
If the command does not exist, it throws an error. When this happens, you can do me and the community a favor by creating a feature request issue of the command you want to be added.
For commands with spaces
type nul > which creates an empty file in windows as
touch does in linux and is saved in the command list, a windows user of this package would have to do the following:
const spawnSync = ;
cross-cmd changes the command 'type nul >' depending on the os.
It is important to confirm that a command exists before using it in your package. You can run the following to confirm that a command exists:
node ./node_modules cross_cmd <command-name> --help
Or find all commands available here.
Issues and Contributions
Your contribution to this project would be highly appreciated. Could be a documentation issue, pull request, feature request, they are all welcome.