当前位置:网站首页>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

边栏推荐
- 【Bluetooth蓝牙开发】八、BLE协议之传输层
- 8、 QoS queue scheduling and message discarding
- 微信小程序开发入门,自己开发小程序
- With the help of domestic chip manufacturers, the shipment of white brand TWS headphones has reached 600million in 2020
- 中国科学家首次用DNA构造卷积人工神经网络,可完成32类分子模式识别任务,或用于生物标志物信号分析和诊断
- Baidu search is in line with expectations, but it involves the black hat strategy of the external chain. What is the reason?
- Leetcode interview question 02.07. Linked list intersection [knowledge points: Double pointers, stack]
- 这种动态规划你见过吗——状态机动态规划之股票问题(下)
- 关于一些小需求,用案例方式记录
- 如何高效、精准地进行图片搜索?看看轻量化视觉预训练模型
猜你喜欢

蚂蚁集团境外站点 Seata 实践与探索

MySQL 是如何归档数据的呢?

Research on weapon equipment attribute extraction based on attribute word completion

What technology is needed for applet development

微信小程序开发公司你懂得选择吗?

openEuler Embedded SIG | 分布式软总线

Meta opens the project aria pilot dataset and will develop real-time 3D maps in the future

基于复杂网络的大群体应急决策专家意见与信任信息融合方法及应用

LeetCode链表问题——142.环形链表II(一题一文学会链表)

日志瘦身神操作:从5G优化到1G到底是怎么做到的!(荣耀典藏版)
随机推荐
基于对象的实时空间音频渲染丨Dev for Dev 专栏
MSI Bao'an factory is on fire! Official response: no one was injured, and the production line will not be affected!
Uniapp progress bar customization
实现瀑布流效果
【英雄哥七月集训】第 28天:动态规划
Query Oracle view creation statement and how to insert data into the view [easy to understand]
基于BRNN的政务APP评论端到端方面级情感分析方法
开放式耳机哪个品牌好、性价比最高的开放式耳机排名
C#流程控制语句
[brother hero July training] day 28: dynamic planning
不用Swagger,那我用啥?
Chinese patent keyword extraction based on LSTM and logistic regression
Why on earth is it not recommended to use select *?
基于知识元的外文专利文献知识描述框架
[极客大挑战 2019]Secret File&文件包含常用伪协议以及姿势
针对下一代Chromebook,联发科推出新款芯片组MT8192和MT8195
Assign a string pointer to an array [easy to understand]
Detailed explanation of JVM memory layout (glory collection version)
详解visual studio 2015在局域网中远程调试程序
酷派主动终止针对小米公司的专利侵权诉讼