当前位置:网站首页>Two global variables__ Dirname and__ Further introduction to common functions of filename and FS modules
Two global variables__ Dirname and__ Further introduction to common functions of filename and FS modules
2022-07-28 21:53:00 【M78_ Domestic 007】
The authorities provided it to us __dirname and __filename These two variables , Note that their values are strings .
__dirname: On behalf of the current js The path to the directory where the file is located ( Absolute path )
__filename: On behalf of the current js Path to file ( Absolute path )
Show me : Create a new one js file , Print these two variables .
console.log(__dirname);
console.log(__filename);
Terminal results :
fs Module common functions
Read the file fs.readFile(path,(err,data)=>{})
Parameter description :
path: The path to read the file ( It could be an absolute path , Can be a relative path );
err: The information returned from reading failure ;
data: Read the binary type data returned successfully , We can go through toString() Method to string .
Code demonstration :
First create one under the same directory test.txt, Text file with test text , We'll use readFile() Read .
const fs=require("fs")
fs.readFile("./test.txt",(err,data)=>{
console.log(err,data.toString());
})
The terminal prints the results :
Read file successful err return null,data Return the contents of the file , Because in the toString() Convert to string , We can see the test text , If not, binary data will be printed .
write file fs.writeFile(path,data,callback(err))
Parameter description :
path: For the path we want to write to the file ;
data: The data to be written ;
callback(err): Callback function , When writing to a file fails ,err Return error message .
Note that when we write a file , If the file already exists in the write path , Then our new writing will overwrite the original , If not, create the file .
Code demonstration :
When there is no such file
fs.writeFile("./newtxt.txt"," newly build txt",(err)=>{
// If the failure returns an error message
console.log(err);
})
function js file , At this time, the folder has been successfully created newtxt.txt
When the folder already exists
fs.writeFile("./newtxt.txt"," I established it for the second time txt",(err)=>{
// If the failure returns an error message
console.log(err);
})
Run code , You can see that the content of the text has changed
Delete file fs.unlink(path,callback(err))
Parameter description :
path: Delete the path of the file , For the string
callback(err): Callback function ,err Error message when deleting file , success err by null
Code demonstration :
fs.unlink("./newtxt.txt",(err)=>{
console.log(err);
})
Running results :
You can see the file written above newtxt.txt It has been deleted .
Additional content fs.appendFile(path,content,callback(err))
Parameter description :
path: The path of the append file , In the form of string ;
content: Additional content
callback(err): Callback function ,err Error message returned for append failure , Append succeeded err by null
Code demonstration :
fs.appendFile("./test.txt"," I am a new content ",(err)=>{
console.log(err);
})
Running results :
If path The path does not exist in the folder , Then it will automatically create this file for us .
for example :
Create directory fs.mkdir(path,callback(err))
Parameter description :
path: The path to create the directory , The format is also a string ;
callback: Callback function , Parameters err Error message returned for creation failure ;
Code demonstration :
fs.mkdir(__dirname+"/newfile",(err)=>{
//dirname by node Path to folder
console.log(err);
})
Running results :
Move / Rename a file or directory fs.rename(oldpath,newpath,callback(err))
Parameter description :
oldpath, Original catalogue / The full path and name of the file ;
newpath, New catalog / The full path and name of the file ; If the new path is the same as the original path , Only the file name is different , It's about renaming
callback(err), Operation completion callback function ;err Operation failed object
Moving files has a bug: The new path and the old path must be the same root disk
Code demonstration :
// rename
let oldpath=__dirname+"/test.txt"
let newpath=__dirname+"/newtest.txt"
fs.rename(oldpath,newpath,(err)=>{
console.log(" Rename successful ");
})
// Move
let oldpath1=__dirname+"/tes.txt"
let newpath1=__dirname+"/newfile/tes.txt"
fs.rename(oldpath1,newpath1,(err)=>{
console.log(" Mobile success ");
})
Running results :
Copy files fs.copyFile(oldpath, newpath, callback(err) )
Parameter description :
oldpath, The full path of the original file ;
newpath, The full path of the new file ;
callback(err), Operation completion callback function ;err Operation failed object
Code demonstration :
let oldpath=__dirname+"/newtest.txt"
let newpath=__dirname+"/newfile/newtest.txt"
fs.copyFile(oldpath,newpath,(err)=>{
console.log(" Success copy ");
})
Running results : The contents of the two files are the same
边栏推荐
- LeetCode·581.最短无序连续子数组·双指针
- 基于对象的实时空间音频渲染丨Dev for Dev 专栏
- Skiasharp's WPF self drawn drag ball (case version)
- Apple M1 processor details: performance and energy efficiency have doubled, and Intel Core i9 is no match!
- 基于Paragraph-BERT-CRF的科技论文摘要语步功能信息识别方法研究
- Detailed explanation of JVM memory layout (glory collection version)
- Versailles ceiling: "the monthly salary of two years after graduation is only 35K, which is really unpromising ~ ~"
- 比UUID更快更安全NanoID到底是怎么实现的?(荣耀典藏版)
- It is said that Microsoft has obtained the supply license for Xianghua! Will Huawei usher in the full lifting of the ban?
- 八、QOS队列调度与报文丢弃
猜你喜欢
不用Swagger,那我用啥?
Object based real-time spatial audio rendering - Dev for dev column
中文招聘文档中专业技能词抽取的跨域迁移学习
openEuler Embedded SIG | 分布式软总线
LeetCode链表问题——面试题02.07.链表相交(一题一文学会链表)
磷脂偶联抗体/蛋白试剂盒的存储与步骤
fluke dtx-1800测试精度有必要进行原厂校准吗?
Summary of 29 typical problems in Devops planning and construction of securities enterprises based on containerized PAAS platform
顺序表的实现
[极客大挑战 2019]Secret File&文件包含常用伪协议以及姿势
随机推荐
8、 QoS queue scheduling and message discarding
NTP server time (view server time)
Object based real-time spatial audio rendering - Dev for dev column
LT7911D Type-C/DP转mipi 方案成熟可提供技术支持
传微软已获得向华为供货许可!华为将迎来全面解禁?
Pytorch学习记录(三):随机梯度下降、神经网络与全连接
中文招聘文档中专业技能词抽取的跨域迁移学习
The general strike of three factories in St France may make the shortage of chips more serious!
Research on weapon equipment attribute extraction based on attribute word completion
With the help of domestic chip manufacturers, the shipment of white brand TWS headphones has reached 600million in 2020
Pytorch learning record (4): over fitting, convolution neural network CNN
B+ tree height calculation of MySQL
Cross domain transfer learning of professional skill word extraction in Chinese recruitment documents
磷脂偶联抗体/蛋白试剂盒的存储与步骤
Construction of Chinese traditional embroidery classification model based on xception TD
Assign a string pointer to an array [easy to understand]
HCIA综合实验(以华为eNSP为例)
[英雄星球七月集训LeetCode解题日报] 第28日 动态规划
酷派主动终止针对小米公司的专利侵权诉讼
Meeting notice of OA project (Query & whether to attend the meeting & feedback details)