Get Current Working Directory for Yeoman and Inquirer.js

by

Today I’ve been working on a Yeoman generator for Sequence themes. It’s my first time creating a Yeoman generator and so far so good. One small area I got stuck on though was getting the name of the current working directory and using it as a default for a generator question.

When you launch the Sequence theme generator using the command yo sequence, the first question is “what do you want to call your Sequence theme?”. I wanted the default option to be the same as the name of the current working directory. I couldn’t find how to do this in the documentation for Yeoman or Inquirer.js (which Yeoman utilises for prompts such as these) but that’s mainly because its functionality that belongs to Node.js (which both of these technologies are built upon). As I’m unfamiliar with Node.js and it didn’t even cross my mind, my Google searches didn’t return an answer.

Here’s a little snippet to get the name of the current working directory for your Yeoman and/or Inquirer.js prompts:

var prompts = [
  {
    name: 'themeName',
    message: 'What do you want to call your Sequence theme?',
    default: process.cwd().split(path.sep).pop()
  }
]

process.cwd() will get the path to the current working directory, in my case /Users/Ian/Sites/sequence-theme, split it into an array using / as a path separator ['Users', 'Ian', 'Sites', 'sequence-theme'], and then return the last entry in the array sequence-theme (the directory name I wanted).

Written by Ian Lunn

is a WordPress & Front-end Developer producing high quality responsive websites and exceptional user experience. Author of CSS3 Foundations and creator of Hover.css & Sequence.js.

Comments

Show comments...
Hire Ian to work on your project