@nurliman/file-exists-cli
Version:
Check if a file exists
101 lines (96 loc) • 2.32 kB
JavaScript
// src/index.ts
import fs from "node:fs";
import path from "node:path";
// package.json
var version = "1.0.2";
// src/index.ts
import meow from "meow";
var cli = meow(
`
Usage
$ exists <file-path> [options]
Options
--reverse, -r Reverse output
--silent, -s Silent output, except \`onError\` command
--onError Execute command on error
--version Show version
--help Show this help message
Examples
$ exists ./package.json --reverse
`,
{
importMeta: import.meta,
flags: {
reverse: {
type: "boolean",
shortFlag: "r",
default: false
},
silent: {
type: "boolean",
shortFlag: "s",
default: false
},
version: {
type: "boolean",
default: false,
isMultiple: false,
isRequired: false,
shortFlag: "v"
},
onError: {
type: "string",
default: ""
}
}
}
);
var consola = (type = "log", ...args) => {
if (!cli.flags.silent) {
console[type]?.(...args);
}
};
consola.log = (...args) => consola("log", ...args);
consola.info = (...args) => consola("info", ...args);
consola.error = (...args) => consola("error", ...args);
async function main() {
if (cli.flags.version) {
console.log(version);
return;
}
const filePath = cli.input[0];
const { reverse } = cli.flags;
if (!filePath) {
consola.error("No file path provided.");
return cli.showHelp?.();
}
const isFileExists = fs.existsSync(filePath);
let exitCode;
let message;
if (isFileExists) {
message = `File "${path.resolve(filePath)}" exists.`;
} else {
message = `File "${path.resolve(filePath)}" does not exists.`;
}
if (reverse) {
exitCode = isFileExists ? 1 : 0;
} else {
exitCode = isFileExists ? 0 : 1;
}
consola.info(message);
if (cli.flags.onError && exitCode !== 0) {
consola.info(`Executing command "${cli.flags.onError}"`);
const { execa } = await import("execa");
const onErrorReturn = await execa(cli.flags.onError, {
shell: true,
stdio: "inherit"
});
if (typeof onErrorReturn.exitCode === "number") {
exitCode = onErrorReturn.exitCode;
}
}
process.exit(exitCode);
}
main();
//# sourceMappingURL=index.js.map