当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Node.js process.cwd()用法及代码示例


process.cwd()方法是流程模块的内置应用程序编程接口,用于获取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



相关用法


注:本文由纯净天空筛选整理自anwesha0107大神的英文原创作品 Node.js | process.cwd() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。