Get Current Working Directory for Yeoman and Inquirer.js

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).

Useful? Buy me a coffeeUseful? Buy me a coffee

Ian Lunn is a Front-end Developer with 12 years commercial experience, author of CSS3 Foundations, and graduate of Internet Technology. He creates successful websites that are fast, easy to use, and built with best practices.