📜  Node.js process.cwd() 方法

📅  最后修改于: 2022-05-13 01:56:36.483000             🧑  作者: Mango

Node.js process.cwd() 方法

process.cwd() 方法process 模块的内置应用程序编程接口,用于获取 node.js 进程的当前工作目录。

句法:

process.cwd()

参数:此方法不接受任何参数。

返回值:该方法返回一个字符串,指定 node.js 进程的当前工作目录。

下面的例子说明了在 Node.js 中process.cwd() 方法的使用:

示例 1:

// Node.js program to demonstrate the    
// process.cwd() Method
  
// Include process module
const process = require('process');
  
// Printing current directory
console.log("Current working directory: ",
          process.cwd());

输出:

Current working directory: C:\nodejs\g\process

示例 2:

// Node.js program to demonstrate the    
// process.cwd() Method
  
// Include process module
const process = require('process');
  
// Printing current directory
console.log("Current working directory: ",
          process.cwd());
  
try {
      
  // Change working directory
  process.chdir('../');
  console.log("Working directory after changing"
      + " directory: ", process.cwd());
} catch (err) {
     
  // printing error if occurs
  console.error("error occured while changing"
          + " directory: ", err);
}

输出:

Current working directory: C:\nodejs\g\process
Working directory after changing directory: C:\nodejs\g\os

注意:上面的程序将使用node filename.js命令编译和运行。

参考:
https://nodejs.org/api/process.html#process_process_cwd