Home > Article > Web Front-end > Introduction to the usage of fs file system in node.js
This article brings you an introduction to the usage of the fs file system in node.js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
fs file system module performs some read and write operations on system files and directories.
The methods in the module have asynchronous and synchronous versions. For example, the function for reading file content includes asynchronous fs.readFile()
and synchronous fs.readFileSync()
.
The last parameter of the asynchronous method function is the callback function, and the first parameter of the callback function contains error information (error).
It is recommended that you use asynchronous methods. Compared with synchronization, asynchronous methods have higher performance, faster speed, and no blocking.
Create file
fs.writeFile(filename,data,[options],function(err){})
If the file exists, write The imported content will overwrite the old file content
filename (String) 文件名称 data (String | Buffer) 将要写入的内容,可以使字符串 或 buffer数据。 options (Object) option数组对象,包含 callback {Function} 回调,传递一个异常参数err。
Append file
fs.appendFile(path,data,[options],function(err){})
name : 文件名 str : 添加的字段 encode : 设置编码 callback : 回调函数 ,传递一个异常参数err
Read file
fs.readFile(path,options,function(err,data){})
filename 具体的文件保存路径地址 [options] 具体选项配置,包括数据的编码方式, callback为具体的回调函数,进行相应的错误捕捉及提示。
Whether the file exists
fs.exists (path, function(exists){})
path 欲检测的文件路径 callback 回调
Note that the parameters of this callback are inconsistent with those of other Node.js callbacks. It is not recommended to use fs.exists() to detect whether the file exists before calling fs.open, fs.readFile(), fs.writeFile(). Doing so can cause a race condition because other processes may modify the file between calls. Instead, users should open/read/write files directly and handle errors when the file does not exist.
Delete files
fs.unlink(path,function(err){})
path - 文件路径 callback - 回调函数,err
Create folder
fs.mkdir(name,function (err){})
path - 文件路径。 callback - 回调函数,err,异步地创建目录。 完成回调只有一个可能的异常参数。
Delete folder
fs.rmdir(path,function(err){})
path - 文件路径。 callback - 回调函数,没有参数。
Read folder
fs.readdir(path,function(err,files){})
path - 文件路径。 callback - 回调函数,回调函数带有两个参数err, files,err 为错误信息,files 为 目录下的文件数组列表
Change the name
fs.rename(oldname,newname,function(err){})
Modify the file name to change the file storage path.
The above is the detailed content of Introduction to the usage of fs file system in node.js. For more information, please follow other related articles on the PHP Chinese website!