Files
30-seconds-of-code/snippets/has-flags.md
Angelos Chalaris 61200d90c4 Kebab file names
2023-04-27 21:58:35 +03:00

27 lines
771 B
Markdown

---
title: Check if process arguments contain flags
tags: node
cover: white-tablet
firstSeen: 2018-01-01T18:24:43+02:00
lastUpdated: 2020-10-22T20:23:47+03:00
---
Checks if the current process's arguments contain the specified flags.
- Use `Array.prototype.every()` and `Array.prototype.includes()` to check if `process.argv` contains all the specified flags.
- Use a regular expression to test if the specified flags are prefixed with `-` or `--` and prefix them accordingly.
```js
const hasFlags = (...flags) =>
flags.every(flag =>
process.argv.includes(/^-{1,2}/.test(flag) ? flag : '--' + flag)
);
```
```js
// node myScript.js -s --test --cool=true
hasFlags('-s'); // true
hasFlags('--test', 'cool=true', '-s'); // true
hasFlags('special'); // false
```