1

I am trying to change the default folder in node.js. I went to the following link in the node.js documentation: https://nodejs.org/api/process.html#process_process_chdir_directory

I then generated the following code in a .js file:

console.log('Starting directory: ${process.cwd()}');
try {
  process.chdir('C:\Users\HalvorSD\node-party');
  console.log('New directory: ${process.cwd()}');
} catch (err) {
  console.error('chdir: ${err}');
}

I get the error thrown in my console. The directory does exist so that's not the problem. Is my directory formatting incorrect or what's my issue?

I am trying to change the default from C:/Windows/System32/ to what I have above. Any help would be much appreciated.

0

2 Answers 2

2

JavaScript uses \ for String escape sequences. Use \\ for a literal backslash:

process.chdir('C:\\Users\\HalvorSD\\node-party');

Alternatively use path.join for cross-platform paths:

const path = require('path')
process.chdir(path.join('C', 'Users', 'HalvorSD', 'node-party'));
Sign up to request clarification or add additional context in comments.

3 Comments

Do you know how to get it to permanently change on load? It still loads to /windows/system32/ when I open node.js
I don't think so - you need to run process.chdir right at the start of your program.
Would it cause problems if I put it in the system32 folder?
1

If you are going to change default directory for "Node.js command prompt" every time, when you launch it, then (Windows case)

  1. go the directory where NodeJS was installed
  2. find file nodevars.bat
  3. open it with editor as administrator
  4. change the default path in the row which looks like

    if "%CD%\"=="%~dp0" cd /d "%HOMEDRIVE%%HOMEPATH%"
    

with your path. It could be for example

    if "%CD%\"=="%~dp0" cd /d "c://MyDirectory/"

if you mean to change directory once when you launched "Node.js command prompt", then execute the following command in the Node.js command prompt:

     cd c:/MyDirectory/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.