Node.js v0.10.18 手册 & 文档
目录
- File System
- fs.rename(oldPath, newPath, callback)
- fs.renameSync(oldPath, newPath)
- fs.ftruncate(fd, len, callback)
- fs.ftruncateSync(fd, len)
- fs.truncate(path, len, callback)
- fs.truncateSync(path, len)
- fs.chownSync(path, uid, gid)
- fs.fchown(fd, uid, gid, callback)
- fs.fchownSync(fd, uid, gid)
- fs.lchown(path, uid, gid, callback)
- fs.lchownSync(path, uid, gid)
- fs.chmod(path, mode, callback)
- fs.chmodSync(path, mode)
- fs.fchmod(fd, mode, callback)
- fs.fchmodSync(fd, mode)
- fs.lchmod(path, mode, callback)
- fs.lchmodSync(path, mode)
- fs.stat(path, callback)
- fs.lstat(path, callback)
- fs.fstat(fd, callback)
- fs.statSync(path)
- fs.lstatSync(path)
- fs.fstatSync(fd)
- fs.link(srcpath, dstpath, callback)
- fs.linkSync(srcpath, dstpath)
- fs.symlink(srcpath, dstpath, [type], callback)
- fs.symlinkSync(srcpath, dstpath, [type])
- fs.readlink(path, callback)
- fs.readlinkSync(path)
- fs.realpath(path, [cache], callback)
- fs.realpathSync(path, [cache])
- fs.unlink(path, callback)
- fs.unlinkSync(path)
- fs.rmdir(path, callback)
- fs.rmdirSync(path)
- fs.mkdir(path, [mode], callback)
- fs.mkdirSync(path, [mode])
- fs.readdir(path, callback)
- fs.readdirSync(path)
- fs.close(fd, callback)
- fs.closeSync(fd)
- fs.open(path, flags, [mode], callback)
- fs.openSync(path, flags, [mode])
- fs.utimes(path, atime, mtime, callback)
- fs.utimesSync(path, atime, mtime)
- fs.utimes(path, atime, mtime, callback)
- fs.utimesSync(path, atime, mtime)
- fs.futimes(fd, atime, mtime, callback)
- fs.futimesSync(fd, atime, mtime)
- fs.futimes(fd, atime, mtime, callback)
- fs.futimesSync(fd, atime, mtime)
- fs.fsync(fd, callback)
- fs.fsyncSync(fd)
- fs.write(fd, buffer, offset, length[, position], callback)
- fs.write(fd, data[, position[, encoding]], callback)
- fs.writeSync(fd, buffer, offset, length[, position])
- fs.writeSync(fd, data[, position[, encoding]])
- fs.read(fd, buffer, offset, length, position, callback)
- fs.readSync(fd, buffer, offset, length, position)
- fs.readFile(filename, [options], callback)
- fs.readFileSync(filename, [options])
- fs.writeFile(filename, data, [options], callback)
- fs.writeFileSync(filename, data, [options])
- fs.appendFile(filename, data, [options], callback)
- fs.appendFileSync(filename, data, [options])
- fs.watchFile(filename, [options], listener)
- fs.unwatchFile(filename, [listener])
- fs.watch(filename, [options], [listener])
- fs.exists(path, callback)
- fs.existsSync(path)
- Class: fs.Stats
- fs.createReadStream(path, [options])
- Class: fs.ReadStream
- fs.createWriteStream(path, [options])
- Class: fs.WriteStream
- Class: fs.FSWatcher
File System#
稳定度: 3 - 稳定
File I/O is provided by simple wrappers around standard POSIX functions. To
use this module do require('fs')
. All the methods have asynchronous and
synchronous forms.
文件系统模块是一个简单包装的标准 POSIX 文件 I/O 操作方法集。您可以通过调用require('fs')
来获取该模块。文件系统模块中的所有方法均有异步和同步版本。
The asynchronous form always take a completion callback as its last argument.
The arguments passed to the completion callback depend on the method, but the
first argument is always reserved for an exception. If the operation was
completed successfully, then the first argument will be null
or undefined
.
文件系统模块中的异步方法需要一个完成时的回调函数作为最后一个传入形参。
回调函数的构成由您调用的异步方法所决定,通常情况下回调函数的第一个形参为返回的错误信息。
如果异步操作执行正确并返回,该错误形参则为null
或者undefined
。
When using the synchronous form any exceptions are immediately thrown. You can use try/catch to handle exceptions or allow them to bubble up.
如果您使用的是同步版本的操作方法,则一旦出现错误,会以通常的抛出错误的形式返回错误。
你可以用try
和catch
等语句来拦截错误并使程序继续进行。
Here is an example of the asynchronous version:
这里是一个异步版本的例子:
fs.unlink('/tmp/hello', function (err) {
if (err) throw err;
console.log('successfully deleted /tmp/hello');
});
Here is the synchronous version:
这是同步版本的例子:
fs.unlinkSync('/tmp/hello')
console.log('successfully deleted /tmp/hello');
With the asynchronous methods there is no guaranteed ordering. So the following is prone to error:
当使用异步版本时不能保证执行顺序,因此下面这个例子很容易出错:
fs.rename('/tmp/hello', '/tmp/world', function (err) {
if (err) throw err;
console.log('renamed complete');
});
fs.stat('/tmp/world', function (err, stats) {
if (err) throw err;
console.log('stats: ' + JSON.stringify(stats));
});
It could be that fs.stat
is executed before fs.rename
.
The correct way to do this is to chain the callbacks.
fs.stat
有可能在fs.rename
前执行.要等到正确的执行顺序应该用下面的方法:
fs.rename('/tmp/hello', '/tmp/world', function (err) {
if (err) throw err;
fs.stat('/tmp/world', function (err, stats) {
if (err) throw err;
console.log('stats: ' + JSON.stringify(stats));
});
});
In busy processes, the programmer is strongly encouraged to use the asynchronous versions of these calls. The synchronous versions will block the entire process until they complete--halting all connections.
在繁重的任务中,强烈推荐使用这些函数的异步版本.同步版本会阻塞进程,直到完成处理,也就是说会暂停所有的连接.
Relative path to filename can be used, remember however that this path will be
relative to process.cwd()
.
可以使用文件名的相对路径, 但是记住这个路径是相对于process.cwd()
的.
Most fs functions let you omit the callback argument. If you do, a default callback is used that rethrows errors. To get a trace to the original call site, set the NODE_DEBUG environment variable:
大部分的文件系统(fs)函数可以忽略回调函数(callback)这个参数.如果忽略它,将会由一个默认回调函数(callback)来重新抛出(rethrow)错误.要获得原调用点的堆栈跟踪(trace)信息,需要在环境变量里设置NODE_DEBUG.
$ env NODE_DEBUG=fs node script.js
fs.js:66
throw err;
^
Error: EISDIR, read
at rethrow (fs.js:61:21)
at maybeCallback (fs.js:79:42)
at Object.fs.readFile (fs.js:153:18)
at bad (/path/to/script.js:2:17)
at Object.<anonymous> (/path/to/script.js:5:1)
<etc.>
fs.rename(oldPath, newPath, callback)#
Asynchronous rename(2). No arguments other than a possible exception are given to the completion callback.
异步版本的rename函数(2).完成时的回调函数(callback)只接受一个参数:可能出现的异常信息.
fs.renameSync(oldPath, newPath)#
Synchronous rename(2).
同步版本的rename(2).
fs.ftruncate(fd, len, callback)#
Asynchronous ftruncate(2). No arguments other than a possible exception are given to the completion callback.
异步版本的ftruncate(2). 完成时的回调函数(callback)只接受一个参数:可能出现的异常信息.
fs.ftruncateSync(fd, len)#
Synchronous ftruncate(2).
同步版本的ftruncate(2).
fs.truncate(path, len, callback)#
Asynchronous truncate(2). No arguments other than a possible exception are given to the completion callback.
异步版本的truncate(2). 完成时的回调函数(callback)只接受一个参数:可能出现的异常信息.
fs.truncateSync(path, len)#
Synchronous truncate(2).
同步版本的truncate(2).
异步版本的chown.完成时的回调函数(callback)只接受一个参数:可能出现的异常信息.
Asynchronous chown(2). No arguments other than a possible exception are given to the completion callback.
异步版本的chown(2).完成时的回调函数(callback)只接受一个参数:可能出现的异常信息.
fs.chownSync(path, uid, gid)#
Synchronous chown(2).
同步版本的chown(2).
fs.fchown(fd, uid, gid, callback)#
Asynchronous fchown(2). No arguments other than a possible exception are given to the completion callback.
异步版本的fchown(2)。回调函数的参数除了出现错误时有一个错误对象外,没有其它参数。
fs.fchownSync(fd, uid, gid)#
Synchronous fchown(2).
同步版本的fchown(2).
fs.lchown(path, uid, gid, callback)#
Asynchronous lchown(2). No arguments other than a possible exception are given to the completion callback.
异步版的lchown(2)。完成时的回调函数(callback)只接受一个参数:可能出现的异常信息.
fs.lchownSync(path, uid, gid)#
Synchronous lchown(2).
同步版本的lchown(2).
fs.chmod(path, mode, callback)#
Asynchronous chmod(2). No arguments other than a possible exception are given to the completion callback.
异步版的 chmod(2). 完成时的回调函数(callback)只接受一个参数:可能出现的异常信息.
fs.chmodSync(path, mode)#
Synchronous chmod(2).
同步版的 chmod(2).
fs.fchmod(fd, mode, callback)#
Asynchronous fchmod(2). No arguments other than a possible exception are given to the completion callback.
异步版的 fchmod(2). 完成时的回调函数(callback)只接受一个参数:可能出现的异常信息.
fs.fchmodSync(fd, mode)#
Synchronous fchmod(2).
同步版的 fchmod(2).
fs.lchmod(path, mode, callback)#
Asynchronous lchmod(2). No arguments other than a possible exception are given to the completion callback.
异步版的 lchmod(2). 完成时的回调函数(callback)只接受一个参数:可能出现的异常信息.
Only available on Mac OS X.
仅在 Mac OS X 系统下可用。
fs.lchmodSync(path, mode)#
Synchronous lchmod(2).
同步版的 lchmod(2).
fs.stat(path, callback)#
Asynchronous stat(2). The callback gets two arguments (err, stats)
where
stats
is a fs.Stats object. See the fs.Stats
section below for more information.
异步版的 stat(2). 回调函数(callback) 接收两个参数: (err, stats)
,其中
stats
是一个 fs.Stats 对象。 详情请参考 fs.Stats
fs.lstat(path, callback)#
Asynchronous lstat(2). The callback gets two arguments (err, stats)
where
stats
is a fs.Stats
object. lstat()
is identical to stat()
, except that if
path
is a symbolic link, then the link itself is stat-ed, not the file that it
refers to.
异步版的 lstat(2). 回调函数(callback)接收两个参数: (err, stats)
其中
stats
是一个 fs.Stats
对象。 lstat()
与 stat()
相同,区别在于:
若 path
是一个符号链接时(symbolic link),读取的是该符号链接本身,而不是它所
链接到的文件。
fs.fstat(fd, callback)#
Asynchronous fstat(2). The callback gets two arguments (err, stats)
where
stats
is a fs.Stats
object. fstat()
is identical to stat()
, except that
the file to be stat-ed is specified by the file descriptor fd
.
异步版的 fstat(2). 回调函数(callback)接收两个参数: (err, stats)
其中
stats
是一个 fs.Stats
对象。 fstat()
与 stat()
相同,区别在于:
要读取的文件(译者注:即第一个参数)是一个文件描述符(file descriptor) fd
。
fs.statSync(path)#
Synchronous stat(2). Returns an instance of fs.Stats
.
同步版的 stat(2). 返回一个 fs.Stats
实例。
fs.lstatSync(path)#
Synchronous lstat(2). Returns an instance of fs.Stats
.
同步版的 lstat(2). 返回一个 fs.Stats
实例。
fs.fstatSync(fd)#
Synchronous fstat(2). Returns an instance of fs.Stats
.
同步版的 fstat(2). 返回一个 fs.Stats
实例。
fs.link(srcpath, dstpath, callback)#
Asynchronous link(2). No arguments other than a possible exception are given to the completion callback.
异步版的 link(2). 完成时的回调函数(callback)只接受一个参数:可能出现的异常信息。
fs.linkSync(srcpath, dstpath)#
Synchronous link(2).
同步版的 link(2).
fs.symlink(srcpath, dstpath, [type], callback)#
Asynchronous symlink(2). No arguments other than a possible exception are given
to the completion callback.
type
argument can be either 'dir'
, 'file'
, or 'junction'
(default is 'file'
). It is only
used on Windows (ignored on other platforms).
Note that Windows junction points require the destination path to be absolute. When using
'junction'
, the destination
argument will automatically be normalized to absolute path.
异步版的 symlink(2). 完成时的回调函数(callback)只接受一个参数:可能出现的异常信息。
type
可以是 'dir'
, 'file'
, 或者'junction'
(默认是 'file'
),此参数仅用于
Windows 系统(其他系统平台会被忽略)。
注意: Windows 系统要求目标路径(译者注:即 dstpath
参数)必须是一个绝对路径,当使用
'junction'
时,dstpath
参数会自动转换为绝对路径。
fs.symlinkSync(srcpath, dstpath, [type])#
Synchronous symlink(2).
同步版的 symlink(2).
fs.readlink(path, callback)#
Asynchronous readlink(2). The callback gets two arguments (err,
linkString)
.
异步版的 readlink(2). 回调函数(callback)接收两个参数: (err,
linkString)
.
fs.readlinkSync(path)#
Synchronous readlink(2). Returns the symbolic link's string value.
同步版的 readlink(2). 返回符号链接(symbolic link)的字符串值。
fs.realpath(path, [cache], callback)#
Asynchronous realpath(2). The callback
gets two arguments (err,
resolvedPath)
. May use process.cwd
to resolve relative paths. cache
is an
object literal of mapped paths that can be used to force a specific path
resolution or avoid additional fs.stat
calls for known real paths.
异步版的 realpath(2). 回调函数(callback)接收两个参数: (err,
resolvedPath)
. May use process.cwd
to resolve relative paths. cache
is an
object literal of mapped paths that can be used to force a specific path
resolution or avoid additional fs.stat
calls for known real paths.
Example:
示例:
var cache = {'/etc':'/private/etc'};
fs.realpath('/etc/passwd', cache, function (err, resolvedPath) {
if (err) throw err;
console.log(resolvedPath);
});
fs.realpathSync(path, [cache])#
Synchronous realpath(2). Returns the resolved path.
realpath(2) 的同步版本。返回解析出的路径。
fs.unlink(path, callback)#
Asynchronous unlink(2). No arguments other than a possible exception are given to the completion callback.
异步版的 unlink(2). 完成时的回调函数(callback)只接受一个参数:可能出现的异常信息.
fs.unlinkSync(path)#
Synchronous unlink(2).
同步版的 unlink(2).
fs.rmdir(path, callback)#
Asynchronous rmdir(2). No arguments other than a possible exception are given to the completion callback.
异步版的 rmdir(2). 异步版的 link(2). 完成时的回调函数(callback)只接受一个参数:可能出现的异常信息。
fs.rmdirSync(path)#
Synchronous rmdir(2).
同步版的 rmdir(2).
fs.mkdir(path, [mode], callback)#
Asynchronous mkdir(2). No arguments other than a possible exception are given
to the completion callback. mode
defaults to 0777
.
异步版的 mkdir(2)。 异步版的 link(2). 完成时的回调函数(callback)只接受一个参数:可能出现的异常信息。文件 mode
默认为 0777
。
fs.mkdirSync(path, [mode])#
Synchronous mkdir(2).
同步版的 mkdir(2)。
fs.readdir(path, callback)#
Asynchronous readdir(3). Reads the contents of a directory.
The callback gets two arguments (err, files)
where files
is an array of
the names of the files in the directory excluding '.'
and '..'
.
异步版的 readdir(3)。 读取 path 路径所在目录的内容。 回调函数 (callback) 接受两个参数 (err, files)
其中 files
是一个存储目录中所包含的文件名称的数组,数组中不包括 '.'
和 '..'
。
fs.readdirSync(path)#
Synchronous readdir(3). Returns an array of filenames excluding '.'
and
'..'
.
同步版的 readdir(3). 返回文件名数组,其中不包括 '.'
和 '..'
目录.
fs.close(fd, callback)#
Asynchronous close(2). No arguments other than a possible exception are given to the completion callback.
异步版 close(2). 完成时的回调函数(callback)只接受一个参数:可能出现的异常信息.
fs.closeSync(fd)#
Synchronous close(2).
同步版的 close(2).
fs.open(path, flags, [mode], callback)#
Asynchronous file open. See open(2). flags
can be:
异步版的文件打开. 详见 open(2). flags
可以是:
'r'
- Open file for reading. An exception occurs if the file does not exist.'r'
- 以【只读】的方式打开文件. 当文件不存在时产生异常.'r+'
- Open file for reading and writing. An exception occurs if the file does not exist.'r+'
- 以【读写】的方式打开文件. 当文件不存在时产生异常.'rs'
- Open file for reading in synchronous mode. Instructs the operating system to bypass the local file system cache.'rs'
- 同步模式下,以【只读】的方式打开文件. 指令绕过操作系统的本地文件系统缓存.This is primarily useful for opening files on NFS mounts as it allows you to skip the potentially stale local cache. It has a very real impact on I/O performance so don't use this flag unless you need it.
该功能主要用于打开 NFS 挂载的文件, 因为它可以让你跳过默认使用的过时本地缓存. 但这实际上非常影响 I/O 操作的性能, 因此除非你确实有这样的需求, 否则请不要使用该标志.
Note that this doesn't turn fs.open()
into a synchronous blocking call.
If that's what you want then you should be using fs.openSync()
注意: 这并不意味着 fs.open()
变成了一个同步阻塞的请求. 如果你想要一个同步阻塞的请求你应该使用 fs.openSync()
.
'rs+'
- Open file for reading and writing, telling the OS to open it synchronously. See notes for'rs'
about using this with caution.'rs+'
- 同步模式下, 以【读写】的方式打开文件. 请谨慎使用该方式, 详细请查看'rs'
的注释.'w'
- Open file for writing. The file is created (if it does not exist) or truncated (if it exists).'w'
- 以【只写】的形式打开文件. 文件会被创建 (如果文件不存在) 或者覆盖 (如果存在).'wx'
- Like'w'
but fails ifpath
exists.'wx'
- 类似'w'
区别是如果文件存在则操作会失败.'w+'
- Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).'w+'
- 以【读写】的方式打开文件. 文件会被创建 (如果文件不存在) 或者覆盖 (如果存在).'wx+'
- Like'w+'
but fails ifpath
exists.'wx+'
- 类似'w+'
区别是如果文件存在则操作会失败.'a'
- Open file for appending. The file is created if it does not exist.'a'
- 以【附加】的形式打开文件,即新写入的数据会附加在原来的文件内容之后. 如果文件不存在则会默认创建.'ax'
- Like'a'
but fails ifpath
exists.'ax'
- 类似'a'
区别是如果文件存在则操作会失败.'a+'
- Open file for reading and appending. The file is created if it does not exist.'a+'
- 以【读取】和【附加】的形式打开文件. 如果文件不存在则会默认创建.'ax+'
- Like'a+'
but fails ifpath
exists.'ax+'
- 类似'a+'
区别是如果文件存在则操作会失败.
mode
sets the file mode (permission and sticky bits), but only if the file was
created. It defaults to 0666
, readable and writeable.
参数 mode
用于设置文件模式 (permission and sticky bits), 不过前提是这个文件是已存在的. 默认情况下是 0666
, 有可读和可写权限.
The callback gets two arguments (err, fd)
.
该 callback 接收两个参数 (err, fd)
.
The exclusive flag 'x'
(O_EXCL
flag in open(2)) ensures that path
is newly
created. On POSIX systems, path
is considered to exist even if it is a symlink
to a non-existent file. The exclusive flag may or may not work with network file
systems.
排除 (exclusive) 标识 'x'
(对应 open(2) 的 O_EXCL
标识) 保证 path
是一个新建的文件。
POSIX 操作系统上,即使 path
是一个指向不存在位置的符号链接,也会被认定为文件存在。
排除标识在网络文件系统不能确定是否有效。
On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.
在 Linux 上,无法对以追加 (append) 模式打开的文件进行指定位置的写入操作。 内核会忽略位置参数并且总是将数据追加到文件尾部。
fs.openSync(path, flags, [mode])#
Synchronous version of fs.open()
.
fs.open()
的同步版.
fs.utimes(path, atime, mtime, callback)#
fs.utimesSync(path, atime, mtime)#
fs.utimes(path, atime, mtime, callback)#
fs.utimesSync(path, atime, mtime)#
Change file timestamps of the file referenced by the supplied path.
更改 path 所指向的文件的时间戳。
fs.futimes(fd, atime, mtime, callback)#
fs.futimesSync(fd, atime, mtime)#
fs.futimes(fd, atime, mtime, callback)#
fs.futimesSync(fd, atime, mtime)#
Change the file timestamps of a file referenced by the supplied file descriptor.
更改文件描述符 (file discriptor) 所指向的文件的时间戳。
fs.fsync(fd, callback)#
Asynchronous fsync(2). No arguments other than a possible exception are given to the completion callback.
异步版本的 fsync(2)。回调函数仅含有一个异常 (exception) 参数。
fs.fsyncSync(fd)#
Synchronous fsync(2).
fsync(2) 的同步版本。
fs.write(fd, buffer, offset, length[, position], callback)#
Write buffer
to the file specified by fd
.
通过文件标识fd
,向指定的文件中写入buffer
。
offset
and length
determine the part of the buffer to be written.
offset
和length
可以确定从哪个位置开始写入buffer。
position
refers to the offset from the beginning of the file where this data
should be written. If typeof position !== 'number'
, the data will be written
at the current position. See pwrite(2).
position
是参考当前文档光标的位置,然后从该处写入数据。如果typeof position !== 'number'
,那么数据会从当前文档位置写入,请看pwrite(2)。
The callback will be given three arguments (err, written, buffer)
where
written
specifies how many bytes were written from buffer
.
回调中会给出三个参数 (err, written, buffer)
,written
说明从buffer
写入的字节数。
Note that it is unsafe to use fs.write
multiple times on the same file
without waiting for the callback. For this scenario,
fs.createWriteStream
is strongly recommended.
注意,fs.write
多次地在同一个文件中使用而没有等待回调是不安全的。在这种情况下,强烈推荐使用fs.createWriteStream
。
On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.
在 Linux 上,无法对以追加 (append) 模式打开的文件进行指定位置的写入操作。 内核会忽略位置参数并且总是将数据追加到文件尾部。
fs.write(fd, data[, position[, encoding]], callback)#
Write data
to the file specified by fd
. If data
is not a Buffer instance
then the value will be coerced to a string.
把data
写入到文档中通过指定的fd
,如果data
不是buffer对象的实例则会把值强制转化成一个字符串。
position
refers to the offset from the beginning of the file where this data
should be written. If typeof position !== 'number'
the data will be written at
the current position. See pwrite(2).
position
是参考当前文档光标的位置,然后从该处写入数据。如果typeof position !== 'number'
,那么数据会从当前文档位置写入,请看pwrite(2)。
encoding
is the expected string encoding.
encoding
是预期得到一个字符串编码
The callback will receive the arguments (err, written, string)
where written
specifies how many bytes the passed string required to be written. Note that
bytes written is not the same as string characters. See
Buffer.byteLength.
回调会得到这些参数 (err, written, string)
,written
表明传入的string
需要写入的字符串长度。注意字节的写入跟字符串写入是不一样的。请看Buffer.byteLength.
Unlike when writing buffer
, the entire string must be written. No substring
may be specified. This is because the byte offset of the resulting data may not
be the same as the string offset.
与写入buffer
不同,必须写入完整的字符串,截取字符串不是符合规定的。这是因为返回的字节的位移跟字符串的位移是不一样的。
Note that it is unsafe to use fs.write
multiple times on the same file
without waiting for the callback. For this scenario,
fs.createWriteStream
is strongly recommended.
注意,fs.write
多次地在同一个文件中使用而没有等待回调是不安全的。在这种情况下,强烈推荐使用fs.createWriteStream
。
On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.
在 Linux 上,无法对以追加 (append) 模式打开的文件进行指定位置的写入操作。 内核会忽略位置参数并且总是将数据追加到文件尾部。
fs.writeSync(fd, buffer, offset, length[, position])#
fs.writeSync(fd, data[, position[, encoding]])#
Synchronous versions of fs.write()
. Returns the number of bytes written.
同步版本的fs.write()
。返回写入的字节数。
fs.read(fd, buffer, offset, length, position, callback)#
Read data from the file specified by fd
.
从指定的文档标识符fd
读取文件数据。
buffer
is the buffer that the data will be written to.
buffer
是缓冲区,数据将会写入这里。
offset
is the offset in the buffer to start writing at.
offset
是开始向缓冲区 buffer
写入的偏移量。
length
is an integer specifying the number of bytes to read.
length
是一个整形值,指定了读取的字节数。
position
is an integer specifying where to begin reading from in the file.
If position
is null
, data will be read from the current file position.
position
是一个整形值,指定了从哪里开始读取文件,如果position
为null
,将会从文件当前的位置读取数据。
The callback is given the three arguments, (err, bytesRead, buffer)
.
回调函数给定了三个参数, (err, bytesRead, buffer)
, 分别为错误,读取的字节和缓冲区。
fs.readSync(fd, buffer, offset, length, position)#
Synchronous version of fs.read
. Returns the number of bytesRead
.
fs.read
函数的同步版本。 返回bytesRead
的个数。
fs.readFile(filename, [options], callback)#
filename
Stringoptions
Objectencoding
String | Null default =null
flag
String default ='r'
callback
Functionfilename
Stringoptions
Objectencoding
String | Null default =null
flag
String default ='r'
callback
Function
Asynchronously reads the entire contents of a file. Example:
异步读取一个文件的全部内容。举例:
fs.readFile('/etc/passwd', function (err, data) {
if (err) throw err;
console.log(data);
});
The callback is passed two arguments (err, data)
, where data
is the
contents of the file.
回调函数传递了两个参数 (err, data)
, data
就是文件的内容。
If no encoding is specified, then the raw buffer is returned.
如果未指定编码方式,原生buffer就会被返回。
fs.readFileSync(filename, [options])#
Synchronous version of fs.readFile
. Returns the contents of the filename
.
fs.readFile
的同步版本。 返回文件名为 filename
的文件内容。
If the encoding
option is specified then this function returns a
string. Otherwise it returns a buffer.
如果 encoding
选项被指定, 那么这个函数返回一个字符串。如果未指定,则返回一个原生buffer。
fs.writeFile(filename, data, [options], callback)#
filename
Stringdata
String | Bufferoptions
Objectencoding
String | Null default ='utf8'
mode
Number default =438
(aka0666
in Octal)flag
String default ='w'
callback
Functionfilename
Stringdata
String | Bufferoptions
Objectencoding
String | Null default ='utf8'
mode
Number default =438
(aka0666
in Octal)flag
String default ='w'
callback
Function
Asynchronously writes data to a file, replacing the file if it already exists.
data
can be a string or a buffer.
异步的将数据写入一个文件, 如果文件原先存在,会被替换。
data
可以是一个string,也可以是一个原生buffer。
The encoding
option is ignored if data
is a buffer. It defaults
to 'utf8'
.
encoding
选项会被忽视如果 data
不是string而是原生buffer。encoding
缺省为 'utf8'
。
Example:
示例:
fs.writeFile('message.txt', 'Hello Node', function (err) {
if (err) throw err;
console.log('It\'s saved!'); //文件被保存
});
fs.writeFileSync(filename, data, [options])#
The synchronous version of fs.writeFile
.
fs.writeFile
的同步版本。
fs.appendFile(filename, data, [options], callback)#
filename
Stringdata
String | Bufferoptions
Objectencoding
String | Null default ='utf8'
mode
Number default =438
(aka0666
in Octal)flag
String default ='a'
callback
Functionfilename
Stringdata
String | Bufferoptions
Objectencoding
String | Null default ='utf8'
mode
Number default =438
(aka0666
in Octal)flag
String default ='a'
callback
Function
Asynchronously append data to a file, creating the file if it not yet exists.
data
can be a string or a buffer.
异步的将数据添加到一个文件的尾部,如果文件不存在,会创建一个新的文件。
data
可以是一个string,也可以是原生buffer。
Example:
示例:
fs.appendFile('message.txt', 'data to append', function (err) {
if (err) throw err;
console.log('The "data to append" was appended to file!'); //数据被添加到文件的尾部
});
fs.appendFileSync(filename, data, [options])#
The synchronous version of fs.appendFile
.
fs.appendFile
的同步版本。
fs.watchFile(filename, [options], listener)#
稳定性: 2 - 不稳定. 尽可能的话推荐使用 fs.watch 来代替。
Watch for changes on filename
. The callback listener
will be called each
time the file is accessed.
监视filename
指定的文件的改变. 回调函数 listener
会在文件每一次被访问时被调用。
The second argument is optional. The options
if provided should be an object
containing two members a boolean, persistent
, and interval
. persistent
indicates whether the process should continue to run as long as files are
being watched. interval
indicates how often the target should be polled,
in milliseconds. The default is { persistent: true, interval: 5007 }
.
第二个参数是可选的。 如果提供此参数,options
应该是包含两个成员persistent
和interval
的对象,其中persistent
值为boolean类型。persistent
指定进程是否应该在文件被监视(watch)时继续运行,interval
指定了目标文件被查询的间隔,以毫秒为单位。缺省值为{ persistent: true, interval: 5007 }
。
The listener
gets two arguments the current stat object and the previous
stat object:
listener
有两个参数,第一个为文件现在的状态,第二个为文件的前一个状态。
fs.watchFile('message.text', function (curr, prev) {
console.log('the current mtime is: ' + curr.mtime);
console.log('the previous mtime was: ' + prev.mtime);
});
These stat objects are instances of fs.Stat
.
listener
中的文件状态对象类型为fs.Stat
。
If you want to be notified when the file was modified, not just accessed
you need to compare curr.mtime
and prev.mtime
.
如果你只想在文件被修改时被告知,而不是仅仅在被访问时就告知,你应当在listener
回调函数中比较下两个状态对象的mtime
属性。即curr.mtime
和 prev.mtime
.
fs.unwatchFile(filename, [listener])#
稳定性: 2 - 不稳定. 尽可能的话推荐使用 fs.watch 来代替。
Stop watching for changes on filename
. If listener
is specified, only that
particular listener is removed. Otherwise, all listeners are removed and you
have effectively stopped watching filename
.
停止监视文件名为 filename
的文件. 如果 listener
参数被指定, 会移除在fs.watchFile
函数中指定的那一个listener回调函数。 否则, 所有的 回调函数都会被移除,你将彻底停止监视filename
文件。
Calling fs.unwatchFile()
with a filename that is not being watched is a
no-op, not an error.
调用 fs.unwatchFile()
时,传递的文件名为未被监视的文件时,不会发生错误,而会发生一个no-op。
fs.watch(filename, [options], [listener])#
稳定性: 2 - 不稳定的
Watch for changes on filename
, where filename
is either a file or a
directory. The returned object is a fs.FSWatcher.
观察指定路径的改变,filename
路径可以是文件或者目录。改函数返回的对象是 fs.FSWatcher。
The second argument is optional. The options
if provided should be an object
containing a boolean member persistent
, which indicates whether the process
should continue to run as long as files are being watched. The default is
{ persistent: true }
.
第二个参数是可选的. 如果 options
选项被提供那么它应当是一个只包含成员persistent
得对象,
persistent
为boolean类型。persistent
指定了进程是否“只要文件被监视就继续执行”缺省值为
{ persistent: true }
.
The listener callback gets two arguments (event, filename)
. event
is either
'rename' or 'change', and filename
is the name of the file which triggered
the event.
监听器的回调函数得到两个参数 (event, filename)
。其中 event
是 'rename'(重命名)或者 'change'(改变),而 filename
则是触发事件的文件名。
注意事项#
The fs.watch
API is not 100% consistent across platforms, and is
unavailable in some situations.
fs.watch
不是完全跨平台的,且在某些情况下不可用。
可用性#
This feature depends on the underlying operating system providing a way to be notified of filesystem changes.
此功能依赖于操作系统底层提供的方法来监视文件系统的变化。
- On Linux systems, this uses
inotify
. - On BSD systems (including OS X), this uses
kqueue
. - On SunOS systems (including Solaris and SmartOS), this uses
event ports
. On Windows systems, this feature depends on
ReadDirectoryChangesW
.在 Linux 操作系统上,使用
inotify
。- 在 BSD 操作系统上 (包括 OS X),使用
kqueue
。 - 在 SunOS 操作系统上 (包括 Solaris 和 SmartOS),使用
event ports
。 - 在 Windows 操作系统上,该特性依赖于
ReadDirectoryChangesW
。
If the underlying functionality is not available for some reason, then
fs.watch
will not be able to function. For example, watching files or
directories on network file systems (NFS, SMB, etc.) often doesn't work
reliably or at all.
如果系统底层函数出于某些原因不可用,那么 fs.watch
也就无法工作。例如,监视网络文件系统(如 NFS, SMB 等)的文件或者目录,就时常不能稳定的工作,有时甚至完全不起作用。
You can still use fs.watchFile
, which uses stat polling, but it is slower and
less reliable.
你仍然可以调用使用了文件状态调查的 fs.watchFile
,但是会比较慢而且比较不可靠。
文件名参数#
Providing filename
argument in the callback is not supported
on every platform (currently it's only supported on Linux and Windows). Even
on supported platforms filename
is not always guaranteed to be provided.
Therefore, don't assume that filename
argument is always provided in the
callback, and have some fallback logic if it is null.
在回调函数中提供的 filename
参数不是在每一个操作系统中都被支持(当下仅在Linux和Windows上支持)。
即便是在支持的系统中,filename
也不能保证在每一次回调都被提供。因此,不要假设filename
参数总会会在
回调函数中提供,在回调函数中添加检测filename
是否为null的if判断语句。
fs.watch('somedir', function (event, filename) {
console.log('event is: ' + event);
if (filename) {
console.log('filename provided: ' + filename);
} else {
console.log('filename not provided');
}
});
fs.exists(path, callback)#
Test whether or not the given path exists by checking with the file system.
Then call the callback
argument with either true or false. Example:
检查指定路径的文件或者目录是否存在。接着通过 callback
传入的参数指明存在 (true) 或者不存在 (false)。示例:
fs.exists('/etc/passwd', function (exists) {
util.debug(exists ? "存在" : "不存在!");
});
fs.existsSync(path)#
Synchronous version of fs.exists
.
fs.exists
函数的同步版。
Class: fs.Stats#
Objects returned from fs.stat()
, fs.lstat()
and fs.fstat()
and their
synchronous counterparts are of this type.
fs.stat()
, fs.lstat()
和 fs.fstat()
以及他们对应的同步版本返回的对象。
stats.isFile()
stats.isDirectory()
stats.isBlockDevice()
stats.isCharacterDevice()
stats.isSymbolicLink()
(only valid withfs.lstat()
)stats.isFIFO()
stats.isSocket()
stats.isFile()
stats.isDirectory()
stats.isBlockDevice()
stats.isCharacterDevice()
stats.isSymbolicLink()
(仅在与fs.lstat()
一起使用时合法)stats.isFIFO()
stats.isSocket()
For a regular file util.inspect(stats)
would return a string very
similar to this:
对于一个普通文件使用 util.inspect(stats)
将会返回一个类似如下输出的字符串:
{ dev: 2114,
ino: 48064969,
mode: 33188,
nlink: 1,
uid: 85,
gid: 100,
rdev: 0,
size: 527,
blksize: 4096,
blocks: 8,
atime: Mon, 10 Oct 2011 23:24:11 GMT,
mtime: Mon, 10 Oct 2011 23:24:11 GMT,
ctime: Mon, 10 Oct 2011 23:24:11 GMT,
birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
Please note that atime
, mtime
, birthtime
, and ctime
are
instances of Date object and to compare the values of
these objects you should use appropriate methods. For most general
uses getTime() will return the number of
milliseconds elapsed since 1 January 1970 00:00:00 UTC and this
integer should be sufficient for any comparison, however there
additional methods which can be used for displaying fuzzy information.
More details can be found in the MDN JavaScript Reference
page.
请注意 atime
, mtime
, birthtime
, and ctime
是
Date 对象的实例。而且在比较这些对象的值时你应当使用合适的方法。
大部分情况下,使用 getTime() 将会返回自 1 January 1970 00:00:00 UTC 以来逝去的毫秒数,
而且这个整形值应该能满足任何比较的使用条件。但是仍然还有一些额外的方法可以用来显示一些模糊的信息。更多细节请查看
MDN JavaScript Reference 页面。
Stat Time Values#
The times in the stat object have the following semantics:
在状态对象(stat object)中的时间有以下语义:
atime
"Access Time" - Time when file data last accessed. Changed by themknod(2)
,utimes(2)
, andread(2)
system calls.mtime
"Modified Time" - Time when file data last modified. Changed by themknod(2)
,utimes(2)
, andwrite(2)
system calls.ctime
"Change Time" - Time when file status was last changed (inode data modification). Changed by thechmod(2)
,chown(2)
,link(2)
,mknod(2)
,rename(2)
,unlink(2)
,utimes(2)
,read(2)
, andwrite(2)
system calls.birthtime
"Birth Time" - Time of file creation. Set once when the file is created. On filesystems where birthtime is not available, this field may instead hold either thectime
or1970-01-01T00:00Z
(ie, unix epoch timestamp0
). On Darwin and other FreeBSD variants, also set if theatime
is explicitly set to an earlier value than the currentbirthtime
using theutimes(2)
system call.atime
"Access Time" - 文件数据上次被访问的时间.
会被mknod(2)
,utimes(2)
, andread(2)
等系统调用改变。mtime
"Modified Time" - 文件上次被修改的时间。 会被mknod(2)
,utimes(2)
, andwrite(2)
等系统调用改变。ctime
"Change Time" - 文件状态上次改变的时间。 (inode data modification). 会被chmod(2)
,chown(2)
,link(2)
,mknod(2)
,rename(2)
,unlink(2)
,utimes(2)
,read(2)
, andwrite(2)
等系统调用改变。birthtime
"Birth Time" - 文件被创建的时间。 会在文件被创建时生成。 在一些不提供文件birthtime
的文件系统中, 这个字段会被ctime
或1970-01-01T00:00Z
(ie, unix epoch timestamp0
)来填充。 在 Darwin 和其他 FreeBSD 系统变体中, 也将atime
显式地设置成比它现在的birthtime
更早的一个时间值,这个过程使用了utimes(2)
系统调用。
Prior to Node v0.12, the ctime
held the birthtime
on Windows
systems. Note that as of v0.12, ctime
is not "creation time", and
on Unix systems, it never was.
在Node v0.12版本之前, ctime
持有Windows系统的 birthtime
值. 注意在v.0.12版本中, ctime
不再是"creation time", 而且在Unix系统中,他从来都不是。
fs.createReadStream(path, [options])#
Returns a new ReadStream object (See Readable Stream
).
返回一个新的 ReadStream 对象 (详见 Readable Stream
).
options
is an object with the following defaults:
options
是一个包含下列缺省值的对象:
{ flags: 'r',
encoding: null,
fd: null,
mode: 0666,
autoClose: true
}
options
can include start
and end
values to read a range of bytes from
the file instead of the entire file. Both start
and end
are inclusive and
start at 0. The encoding
can be 'utf8'
, 'ascii'
, or 'base64'
.
options
可以提供 start
和 end
值用于读取文件内的特定范围而非整个文件。
start
和 end
都是包含在范围内的(inclusive, 可理解为闭区间)并且以 0 开始。
encoding
可选为 'utf8'
, 'ascii'
或者 'base64'
。
If autoClose
is false, then the file descriptor won't be closed, even if
there's an error. It is your responsibility to close it and make sure
there's no file descriptor leak. If autoClose
is set to true (default
behavior), on error
or end
the file descriptor will be closed
automatically.
如果 autoClose
为 false 则即使在发生错误时也不会关闭文件描述符 (file descriptor)。
此时你需要负责关闭文件,避免文件描述符泄露 (leak)。
如果 autoClose
为 true (缺省值),
当发生 error
或者 end
事件时,文件描述符会被自动释放。
An example to read the last 10 bytes of a file which is 100 bytes long:
一个从100字节的文件中读取最后10字节的例子:
fs.createReadStream('sample.txt', {start: 90, end: 99});
Class: fs.ReadStream#
ReadStream
is a Readable Stream.
ReadStream
是一个可读的流(Readable Stream).
事件: 'open'#
fd
Integer file descriptor used by the ReadStream.fd
整形 ReadStream 所使用的文件描述符。
Emitted when the ReadStream's file is opened.
当文件的 ReadStream 被创建时触发。
fs.createWriteStream(path, [options])#
Returns a new WriteStream object (See Writable Stream
).
返回一个新的 WriteStream 对象 (详见 Writable Stream
).
options
is an object with the following defaults:
options
是一个包含下列缺省值的对象:
{ flags: 'w',
encoding: null,
mode: 0666 }
options
may also include a start
option to allow writing data at
some position past the beginning of the file. Modifying a file rather
than replacing it may require a flags
mode of r+
rather than the
default mode w
.
options
也可以包含一个 start
选项用于指定在文件中开始写入数据的位置。
修改而不替换文件需要 flags
的模式指定为 r+
而不是默值的 w
.
Class: fs.WriteStream#
WriteStream
is a Writable Stream.
WriteStream
是一个可写的流(Writable Stream).
事件: 'open'#
fd
Integer file descriptor used by the WriteStream.fd
整形 WriteStream 所使用的文件描述符。
Emitted when the WriteStream's file is opened.
当 WriteStream 创建时触发。
file.bytesWritten#
The number of bytes written so far. Does not include data that is still queued for writing.
已写的字节数。不包含仍在队列中准备写入的数据。
Class: fs.FSWatcher#
Objects returned from fs.watch()
are of this type.
fs.watch()
返回的对象类型。
watcher.close()#
Stop watching for changes on the given fs.FSWatcher
.
停止观察 fs.FSWatcher
对象中的更改。
事件: 'change'#
event
String The type of fs changefilename
String The filename that changed (if relevant/available)event
字符串 fs 改变的类型filename
字符串 改变的文件名 (if relevant/available)
Emitted when something changes in a watched directory or file. See more details in fs.watch.
当正在观察的目录或文件发生变动时触发。更多细节,详见 fs.watch。
事件: 'error'#
error
Error objecterror
Error 对象
Emitted when an error occurs.
当产生错误时触发