Command line
Utility to execute bash commands
Note:
Executing bash commands from a program is a high security risk
Use a different approach whenever possible
Documentation
http://o-programming-language.org/
Installation
npm install o-command-line
Usage
const { CommandLine } = require('o-command-line')
const Path = require('o-toolbox/src/Path')
const { validation } = require('o-check-list')
class CopyDirectory extends CommandLine {
initialize ({ source, dest }) {
this.source = new Path(source)
this.dest = new Path(dest)
}
// Validate the parameters
// If possible, to prevent code injection validate that parameters are semantically correct,
// not just its types and format
// This example uses 'o-check-list', but any other validation can be used as well
validateParams () {
validation((assure) => {
assure.that(this.source)
.isExistingDirectory()
assure.that(this.dest)
.isExistingDirectory()
})
}
// cp -r "source/*" "dest"
buildCommandString () {
return `cp -r "${ this.source.append('*').toString() }" "${ this.dest.toString() }"`
}
// parse output to convert it to the command result, or throw an error
parseCommandOutput ({ stdoutString, stderrString, status, signal, error }) {
if ( status !== 0 ) {
this.raiseCommandExecutionError({ status, stderrString, error })
}
return stdoutString
}
}
module.exports = CopyDirectory
Execute as the user of the running process
const command = new CopyDirectory({ source: '.', dest: './copy' })
command.execute()
Execute as a user
const command = new CopyDirectory({ uid: 1, source: '.', dest: './copy' })
command.execute()
Execute as a group user
const command = new CopyDirectory({ gid: 1, source: '.', dest: './copy' })
command.execute()
Execute with a timeout expressed in milliseconds
const command = new CopyDirectory({ timeout: 1000, source: '.', dest: './copy' })
command.execute()
The execution can be sync or async, calling
command.execute()
command.executeAsync()
The command line is executed in a new, different process and shell each time The process always has the current working directory as its current working directory The process never receives any environment variable or command line input
If you need to set environment variables, pass command line arguments or change the current working directory, make it part of the command string to mitigate code injection and leaking env vars to a different process
// cp -r "source/*" "dest"
buildCommandString () {
return `export PATH="$(which node):$PATH" && cd ${this.path} && npm install`
}