npm run location

时间:2017-03-18 00:13:45

标签: node.js

我有一个位于project/bin/index.js的节点脚本,我将其执行命令添加到package.json

scripts: {
  "exec": "cd ./bin && npm -i --silent && node index.js"
}

我现在可以从项目中的任何位置运行我的节点脚本。问题是我想要根据我运行这个脚本的位置做一些事情,所以我希望能够从那里告诉我运行npm run exec的位置。可能吗?我怎么能这样做?

__filename__dirnameprocess.cwd()返回脚本路径 - project/bin

1 个答案:

答案 0 :(得分:0)

看起来你不能通过npm脚本直接执行此操作。我的猜测是在运行命令之前npm cd到项目目录(事实证明你可以cd ./binnode bin/index.js)。除非您与package.json位于同一目录中,否则Yarn甚至不允许您运行命令。

"scripts": {
  "exec": "npm i --silent && node bin/index.js $PWD"
}

index.js

console.log({
  __filename,
  __dirname,
  cwd: process.cwd(),
  execPath: process.execPath,
  pwd: process.env.PWD,
  argv: process.argv
});

shell env

Jasons-MBP-2:some-dir jason$ env
PWD=/Users/jason/Development/so/npm-run/some-dir

运行

Jasons-MBP-2:some-dir jason$ npm run exec

> npm-run@1.0.0 exec /Users/jason/Development/so/npm-run
> npm i --silent && node bin/index.js $PWD

结果

{ __filename: '/Users/jason/Development/so/npm-run/bin/index.js',
  __dirname: '/Users/jason/Development/so/npm-run/bin',
  cwd: '/Users/jason/Development/so/npm-run',
  execPath: '/Users/jason/.nvm/versions/node/v6.10.0/bin/node',
  pwd: '/Users/jason/Development/so/npm-run',
  argv:
  [ '/Users/jason/.nvm/versions/node/v6.10.0/bin/node',
    '/Users/jason/Development/so/npm-run/bin/index.js',
    '/Users/jason/Development/so/npm-run' ] }