如何从 nodejs 子进程(在 windows 和 linuxish 中)获取 cwd(当前工作目录) [英] How to get the cwd (current working directory) from a nodejs child process (in both windows and linuxish)

查看:131
本文介绍了如何从 nodejs 子进程(在 windows 和 linuxish 中)获取 cwd(当前工作目录)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过 nodejs 运行一个脚本:

I'm trying to run a script via nodejs that does:

cd ..
doSomethingThere[]

但是,要做到这一点,我需要执行多个子进程并在这些进程之间传递环境状态.我想做的是:

However, to do this, I need to executed multiple child processes and carry over the environment state between those processes. What i'd like to do is:

var exec = require('child_process').exec;
var child1 = exec('cd ..', function (error, stdout, stderr) {
  var child2 = exec('cd ..', child1.environment, function (error, stdout, stderr) {
  });
});

或者至少:

var exec = require('child_process').exec;
var child1 = exec('cd ..', function (error, stdout, stderr) {
  var child2 = exec('cd ..', {cwd: child1.process.cwd()}, function (error, stdout, stderr) {
  });
});

我该怎么做?

推荐答案

以父目录为 cwd 启动子项:

to start child with parent dir as cwd:

var exec = require('child_process').exec;
var path = require('path')

var parentDir = path.resolve(process.cwd(), '..');
exec('doSomethingThere', {cwd: parentDir}, function (error, stdout, stderr) {
  // if you also want to change current process working directory:
  process.chdir(parentDir);
});

更新:如果您想检索孩子的 cwd:

Update: if you want to retrieve child's cwd:

var fs = require('fs');
var os = require('os');
var exec = require('child_process').exec;

function getCWD(pid, callback) {
  switch (os.type()) {
  case 'Linux':
    fs.readlink('/proc/' + pid + '/cwd', callback); break;
  case 'Darwin':
    exec('lsof -a -d cwd -p ' + pid + ' | tail -1 | awk \'{print $9}\'', callback);
    break;
  default:
    callback('unsupported OS');
  }
}

// start your child process
//    note that you can't do like this, as you launch shell process 
//    and shell's child don't change it's cwd:
// var child1 = exec('cd .. & sleep 1 && cd .. sleep 1');
var child1 = exec('some process that changes cwd using chdir syscall');

// watch it changing cwd:
var i = setInterval(getCWD.bind(null, child1.pid, console.log), 100);
child1.on('exit', clearInterval.bind(null, i));     

这篇关于如何从 nodejs 子进程(在 windows 和 linuxish 中)获取 cwd(当前工作目录)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆