文件路径


字符串形式的路径被解释为标识绝对或相对文件名的 UTF-8 字符序列。 相对路径将相对于通过调用 process.cwd() 确定的当前工作目录进行解析。

在 POSIX 上使用绝对路径的示例:

const fs = require('fs');

fs.open('/open/some/file.txt', 'r', (err, fd) => {
  if (err) throw err;
  fs.close(fd, (err) => {
    if (err) throw err;
  });
});

在 POSIX 上使用相对路径的示例(相对于 process.cwd()):

fs.open('file.txt', 'r', (err, fd) => {
  if (err) throw err;
  fs.close(fd, (err) => {
    if (err) throw err;
  });
});

使用 Buffer 指定的路径主要用于将文件路径视为不透明字节序列的某些 POSIX 操作系统。 在此类系统上,单个文件路径可能包含使用多种字符编码的子序列。 与字符串路径一样,Buffer 路径可以是相对的或绝对的:

在 POSIX 上使用绝对路径的示例:

fs.open(Buffer.from('/open/some/file.txt'), 'r', (err, fd) => {
  if (err) throw err;
  fs.close(fd, (err) => {
    if (err) throw err;
  });
});

在 Windows 上,Node.js 遵循独立驱动器工作目录的概念。 当使用不带反斜杠的驱动器路径时,可以观察到此行为。 例如,fs.readdirSync('C:\\') 可能返回与 fs.readdirSync('C:') 不同的结果。 有关详细信息,请参阅此 MSDN 页面

Most fs operations accept filepaths that may be specified in the form of a string, a Buffer, or a URL object using the file: protocol.

String form paths are interpreted as UTF-8 character sequences identifying the absolute or relative filename. Relative paths will be resolved relative to the current working directory as determined by calling process.cwd().

Example using an absolute path on POSIX:

const fs = require('fs');

fs.open('/open/some/file.txt', 'r', (err, fd) => {
  if (err) throw err;
  fs.close(fd, (err) => {
    if (err) throw err;
  });
});

Example using a relative path on POSIX (relative to process.cwd()):

fs.open('file.txt', 'r', (err, fd) => {
  if (err) throw err;
  fs.close(fd, (err) => {
    if (err) throw err;
  });
});

Paths specified using a Buffer are useful primarily on certain POSIX operating systems that treat file paths as opaque byte sequences. On such systems, it is possible for a single file path to contain sub-sequences that use multiple character encodings. As with string paths, Buffer paths may be relative or absolute:

Example using an absolute path on POSIX:

fs.open(Buffer.from('/open/some/file.txt'), 'r', (err, fd) => {
  if (err) throw err;
  fs.close(fd, (err) => {
    if (err) throw err;
  });
});

On Windows, Node.js follows the concept of per-drive working directory. This behavior can be observed when using a drive path without a backslash. For example fs.readdirSync('C:\\') can potentially return a different result than fs.readdirSync('C:'). For more information, see this MSDN page.