• Node.js Video Tutorials

Node.js - os.userInfo() 方法



Node.js 的 os.userInfo() 方法屬於 os 模組,它返回一個包含當前有效使用者資訊的物件,例如 'username'、'uid'、'gid'、'shell''homedir'

如果使用者沒有 usernamehomedir,則會丟擲 SystemErroros.userInfo() 方法返回的物件中名為 'homedir' 的屬性值由作業系統提供。

以下是返回物件屬性的描述。

  • uid − 使用者識別符號,用於指定當前有效使用者。

  • gid − 組 ID;它是將使用者連結到其他具有某些共同點的使用者的識別符號。

  • username − 指定當前有效使用者的使用者名稱。

  • homedir − 指定當前有效使用者的 home 目錄。

  • shell − 當前有效使用者正在使用的命令列直譯器。

語法

以下是 Node.js os.userInfo() 方法 的語法 −

os.userInfo([options])

引數

此方法僅接受一個引數 options,它是可選引數。

  • encoding 指定返回資料的字元編碼。如果 encoding 設定為 'buffer',則 username、shellhomedir 的值將是 'Buffer' 的例項。如果 encoding 設定為 'utf8',則值將是 'utf8' 的例項。預設情況下,例項為 'utf8'。

返回值

此方法返回的物件包含名為 'username'、'uid'、'gid'、'shell''homedir' 的屬性。而在 Windows 上,'uid''gid'−1'shell'null

示例

當沒有引數傳遞給方法時,它將採用預設值 'utf8',返回物件屬性的值將是 'Buffer' 例項。

在以下示例中,我們嘗試透過將 Node.js userInfo() 方法 記錄到 控制檯 來列印當前有效使用者資訊。

const os = require('os');

console.log(os.userInfo());

輸出

{ 
   uid: 1000,
   gid: 1000,
   username: 'webmaster',homedir: '/home/webmaster',
   shell: '/bin/bash' 
}

注意 − 為了獲得準確的結果,最好在本地執行上述程式碼。

執行上述程式後,os.userInfo() 方法 返回一個物件,其中包含有關當前有效使用者的的資訊,如下面的輸出所示。

{
   uid: -1,
   gid: -1,
   username: 'Lenovo',
   homedir: 'C:\\Users\\Lenovo',
   shell: null
}

示例

如果 os.userInfo() 方法'encoding' 設定為 'utf8',則返回物件屬性的值將是 'Buffer' 例項。

在以下示例中,我們嘗試將 encoding 值指定為 'utf8'。然後我們列印當前有效使用者資訊。

const os = require('os');

var option = {
    encoding: 'utf8'
};

console.log(os.userInfo(option));

輸出

{ 
   uid: 1000,
   gid: 1000,
   username: 'webmaster',
   homedir: '/home/webmaster',
   shell: '/bin/bash' 
}

注意 − 為了獲得準確的結果,最好在本地執行上述程式碼。

執行上述程式後,os.userInfo() 方法 返回的物件列印了 'username'、'uid'、'gid'、'shell''homedir' 的值作為 'utf8' 例項。

{
   uid: -1,
   gid: -1,
   username: 'Lenovo',
   homedir: 'C:\\Users\\Lenovo',
   shell: null
}

示例

在以下示例中,我們嘗試將 encoding 值指定為 'buffer'。然後我們透過將 userInfo() 方法記錄到控制檯來返回當前有效使用者資訊。

const os = require('os');

var option = {
   encoding: 'buffer'
};

console.log(os.userInfo(option));

輸出

{ 
   uid: 1000,
   gid: 1000,
   username: <Buffer 77 65 62 6d 61 73 74 65 72>,
   homedir: <Buffer 2f 68 6f 6d 65 2f 77 65 62 6d 61 73 74 65 72>,
   shell: <Buffer 2f 62 69 6e 2f 62 61 73 68> 
}

注意 − 為了獲得準確的結果,最好在本地執行上述程式碼。

執行上述程式後,os.userInfo() 方法 返回的物件列印了 'username'、'uid'、'gid'、'shell''homedir' 的值作為 'buffer' 例項。

{
  uid: -1,
  gid: -1,
  username: <Buffer 4c 65 6e 6f 76 6f>,
  homedir: <Buffer 43 3a 5c 55 73 65 72 73 5c 4c 65 6e 6f 76 6f>,
  shell: null
}
nodejs_os_module.htm
廣告