简体   繁体   English

如何在Node.js中为请求设置当前工作目录?

[英]How to set the current working directory for a request in Node.js?

I know I can change the process directory using: 我知道我可以使用以下方式更改进程目录:

process.chdir('/temp/foo');

but I don't want to change the directory for all requests. 但我不想更改所有请求的目录。

I would like to use a different working directory based on the request coming in. For example if the request is for an image, I want to change the working directory to the image directory. 我想根据传入的请求使用其他工作目录。例如,如果请求是针对图像的,我想将工作目录更改为图像目录。 If the request is for an upload, I want to change the current working directory to the upload folder. 如果请求上传,我想将当前工作目录更改为上载文件夹。

I have some other files in these folders specific to the type of request and it would be easier if I can set the current working directory for each request. 我在这些文件夹中还有一些特定于请求类型的其他文件,如果我可以为每个请求设置当前工作目录,则会更容易。

I do not want to change the working directory for all other requests being processed by the same server. 我不想更改同一服务器正在处理的所有其他请求的工作目录。 Each request's working directory should be specific to that request. 每个请求的工作目录应特定于该请求。

When working with any path references just prepend the "working" directory: 使用任何路径引用时,只需在“工作”目录前添加:

function request1() {
  var workingDir = 'prefered/working/path';
  var path = path.resolve(workingDir, 'file.ext');
  var stats = fs.statSync(path);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM