ciso
ciso

Reputation: 3050

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.

Upvotes: 1

Views: 2059

Answers (1)

Sukima
Sukima

Reputation: 10074

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);
}

Upvotes: 1

Related Questions