当前位置:Gxlcms > JavaScript > Node.js文件操作方法汇总_node.js

Node.js文件操作方法汇总_node.js

时间:2021-07-01 10:21:17 帮助过:5人阅读

Node.js和其他语言一样,也有文件操作。先不说node.js中的文件操作,其他语言的文件操作一般也都是有打开、关闭、读、写、文件信息、新建删除目录、删除文件、检测文件路径等。在node.js中也是一样,也都是这些功能,可能就是api与其他语言不太一样。

一、同步、异步打开关闭

其中的flags其他语言也会有.其实主要分3部分 r、w、a.和C中的差不多。

1.r —— 以只读方式打开文件,数据流的初始位置在文件开始
2.r+ —— 以可读写方式打开文件,数据流的初始位置在文件开始
3.w ——如果文件存在,则将文件长度清0,即该文件内容会丢失。如果不存在,则尝试创建它。数据流的初始位置在文件开始
4.w+ —— 以可读写方式打开文件,如果文件不存在,则尝试创建它,如果文件存在,则将文件长度清0,即该文件内容会丢失。数据流的初始位置在文件开始
5.a —— 以只写方式打开文件,如果文件不存在,则尝试创建它,数据流的初始位置在文件末尾,随后的每次写操作都会将数据追加到文件后面。
6.a+ ——以可读写方式打开文件,如果文件不存在,则尝试创建它,数据流的初始位置在文件末尾,随后的每次写操作都会将数据追加到文件后面。

二、读写

1.简单文件读写

"C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" F:\nodejs\node.exe SimpleReadWrite.js
Config Saved.
Config Loaded.
Max Files: 20
Max Connections: 15
Root Path: /webroot

Process finished with exit code 0

2.同步读写

"C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" F:\nodejs\node.exe syncReadWrite.js
Wrote olives 7bytes
Wrote celery 7bytes
Wrote carrots 8bytes
read 5bytes
read 5bytes
read 5bytes
read 5bytes
read 2bytes
read 0bytes
Veggies: olives celery carrots     

Process finished with exit code 0

3.异步读写 和同步读写的参数差不多就是多了callback

"C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" F:\nodejs\node.exe asyncReadWrite.js
Wrote: grapes 7bytes
Wrote: banana 7bytes
Wrote: orange 7bytes
Wrote: apple 6bytes
read 5bytes
read 5bytes
read 5bytes
read 5bytes
read 5bytes
read 2bytes
Fruits: grapes banana orange apple  

Process finished with exit code 0

4.流式读写

"C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" F:\nodejs\node.exe StreamReadWrite.js
Wrote: oats 
Wrote: rice 
Wrote: wheat 
File Closed.
Grains: oats rice wheat 
Read 16 bytes of data.
File Closed.

Process finished with exit code 0

个人觉得像这些api用一用感受一下就ok了,遇到了会用就行了。

人气教程排行