prompts
prompts copied to clipboard
Can I use prompts to ask for a file path?
Is your feature request related to a problem?
Can I use prompts to ask for a file path? I know that I can prompt for a text
, but the user would not get path autocompletion as they'll usually get in the terminal.
Describe the solution you'd like
I would like to use prompts to ask for a filepath.
Describe alternatives you've considered
I can use the text or autocomplete prompt, but this doesn't seem to give useful autocompletion based on existing files and directories to the user.
You can use fs.access
as an async function for the validate
method. If you need to verify more information you can use fs.stat
.
While this is fairly easy to implement, a bigger issue is the autocompletion. In the past days I tried to come up with some code but I couldn't make it work with absolute AND relative paths.
The path
module abstract paths to URLs, trimming the separator at the end with path.resolve('/nice/path/')
but not with path.normalize('/nice/path/')
, therefor it might be better to implement a function without its use.
Taking @DadiBit's suggestion, I got a simple version working like so:
const { filepath } = await prompts([
{
type: 'text',
name: 'filepath',
message: 'Please enter your [relative] path?',
format: value => path.resolve(__dirname, value),
validate: async value =>
(await fs.access(value).catch(() => false)) === undefined
}
]);
Here, fs.access
fulfills with undefined upon success.
Implemented something similar in my application using fs.exists
.
Would love to see a path type with autocompletion.
{
type: 'text',
name: 'path',
message: 'Please enter a path for your file.',
validate: (value) => {
const exists = fs.existsSync(value);
if (!exists) return 'Please enter a valid file path.';
return true;
},
Making @alexrusselldev solution one line:
validate: value => fs.existsSync(value) || 'Please enter a valid file path.',