Stan Luo
Stan Luo

Reputation: 3889

child_process gives 'Command failed' executing grep

I want to search for existence of a file using child_process in node:

const { exec } = require('child_process');
exec('ls | grep "filename"', (err, result) => {...})

When the filename exists, exec result is fine. But when the filename doesn't exist, I get an error:

Command failed: ls | grep "filename"

In this case, how can I tell if it's an error executing the command, or just because no result is found?

EDIT

Thanks for the advice on not searching for a file this way. The above code is not the actual code, but just a demo piece illustrating my problem with grep. In my actual case I'm searching for keywords in the output by task spooler, thus I used exec and tsp -l | grep ...

Upvotes: 5

Views: 2956

Answers (1)

Travis Clarke
Travis Clarke

Reputation: 6671

You can determine this by looking at the value of err.code in the callback. It is documented in more detail in the Node.js docs.

Since the last command in the pipe is grep, consult the grep manpage for a complete list of status codes to branch your logic appropriately. In your case, grep will return a status code of 1 if no lines were selected (i.e. "there are no results"), so if err.code === 1, then you know no files were matched.

Note: as mentioned by @CharlesDuffy, It should be preferred to achieve your desired file manipulations via the Node.js File System API. Leverage this answer as an alternative for situations where exec is explicitly needed.

Upvotes: 9

Related Questions