I have a unique problem where I need to use Node to iterate over several Unix-style commands and see if they exist in the path
of a Windows installation.
For instance, Windows doesn't support ls
natively. However, supposing someone installed git
and checked to include Unix commands, it would.
I need to know whether or not ls
and other commands are in the system path
.
Right now, I'm using child_process
to run help
on each command. I then check the response of running it. This is messy and dangerous. I don't want to run 30 arbitrary commands from Node:
var spawnSync = require('child_process').spawnSync;
var out = spawnSync('ls', ['/?'], {encoding: 'utf8'});
How else can I check for the existence of these commands?
Any Node. Js version. const fs = require("fs"); let path = "/path/to/something"; fs. lstat(path, (err, stats) => { if(err) return console.
To check if a path is a directory in Node. js, we can use the stat() (asynchronous execution) function or the statSync() (synchronous execution) function from the fs (filesystem) module and then use the isDirectory() method returned from the stats object.
To check the path in synchronous mode in fs module, we can use statSync() method. The fs. statSync(path) method returns the instance of fs. Stats which is assigned to variable stats.
Personally I have found that the command-exists module on npm works great.
npm install command-exists
async
var commandExists = require('command-exists');
commandExists('ls', function(err, commandExists) {
if(commandExists) {
// proceed confidently knowing this command is available
}
});
promise
var commandExists = require('command-exists');
// invoked without a callback, it returns a promise
commandExists('ls')
.then(function(command){
// proceed
}).catch(function(){
// command doesn't exist
});
sync
var commandExistsSync = require('command-exists').sync;
// returns true/false; doesn't throw
if (commandExistsSync('ls')) {
// proceed
} else {
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With