Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grunt - get current calling folder, and not gruntfile current folder

If I have Grunt installed in some folder /foo, but my current folder is /foo/bar/baz, and I run "grunt sometask" from within my current folder, how can I get Grunt (or NodeJS for that matter) to determine my current path? That is to say, how can I programmatically GET the folder I was in when I called grunt?

When I use process.cwd(), I get the path of the gruntfile, ie, "foo", which is not what I want.

I don't have to do this in Grunt specifically, any nodejs-based solution would work.

like image 725
Shukri Adams Avatar asked Jan 08 '23 19:01

Shukri Adams


2 Answers

According to the source code:

By default, all file paths are relative to the Gruntfile

And, voilá, this line of code shows how grunt actually changes the current directory to the path of the Gruntfile:

process.chdir(grunt.option('base') || path.dirname(gruntfile));

However, option --base is there for just that. See docs: http://gruntjs.com/api/grunt.file

If you don't need to do it from inside the Gruntfile, simply run a script that captures the process.cwd() and then execs grunt.

See: https://www.npmjs.com/package/exec

var exec = require('exec');

process.cwd(); // Will have your current path

exec(['grunt', 'mytask'], function(err, out, code) {
  if (err instanceof Error)
    throw err;
  process.stderr.write(err);
  process.stdout.write(out);
  process.exit(code);
});
like image 110
Guilherme Rodrigues Avatar answered Jan 18 '23 07:01

Guilherme Rodrigues


in the Mac or Linex, you can get this by

process.env.PWD

in the windows, unknown

You can edit the grunt-cli to get finish this.

grunt-cli/bin/grunt

require(gruntpath).cli({_originDir:basedir});

then in the gruntfile.js, you can follows:

grunt.option('_originDir')
like image 23
vapour Avatar answered Jan 18 '23 06:01

vapour