prompts icon indicating copy to clipboard operation
prompts copied to clipboard

Can I use prompts to ask for a file path?

Open gsabran opened this issue 3 years ago • 4 comments

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.

gsabran avatar May 28 '21 23:05 gsabran

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.

DadiBit avatar Jul 21 '21 16:07 DadiBit

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.

LordParsley avatar Nov 07 '22 09:11 LordParsley

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;
    },

alexrusselldev avatar Jan 22 '24 09:01 alexrusselldev

Making @alexrusselldev solution one line:

validate: value => fs.existsSync(value) ||  'Please enter a valid file path.',

DadiBit avatar Jan 22 '24 21:01 DadiBit