当前位置:网站首页>This article explains the FS file module and path module in nodejs in detail
This article explains the FS file module and path module in nodejs in detail
2022-07-26 13:18:00 【InfoQ】
1. First time to know Node.js



- V8 The engine is responsible for parsing and executing JavaScript Code
- built-in API It is a special interface provided by the operating environment , Can only be called in the running environment
Node.js brief introduction
- What is? Node.jsNode.js It's based on Chrome V8 EngineJavaScript Running environmentOfficial website address https://nodejs.org/zh-cn/
- Node.js Medium JavaScript Running environment
- Browser is JavaScript The front end running environment of
- Node.js yes JavaScript The back end running environment of
- Node.js Cannot call DOM and BOM Browser built in API
- Node.js What can be done
- a be based on Express frame http://www.expressjs.com.cn/ You can quickly build Web application
- b be based on Electron frame https://electronjs.org/ Can build cross platform desktop applications
- c be based on restify frame http://restify.com/ You can quickly build API Interface project
- d Read, write and operate the database 、 Create practical command line tools to assist front-end development 、etc…
- Node.js How to learn
- In the browser JavaScript Learning path
- JavaScript Basic grammar + Browser built in API(DOM + BOM) + Third party Library (jQuery、art-template etc. )
- Node.js The learning path of JavaScript Basic grammar + Node.js built-in API(fs、path、http etc. )+ The third party API modular (express、mysql etc. )
- , You can quickly navigate to the last command executed .
- tab key, You can quickly complete the path of the file ( First enter the first word , And then use tab key , Can quickly complete the path )
- ESC, You can quickly clear the entered commands
- cls, Empty powershell panel
2.fs File system module
What is? fs File system module
const fs = require("fs")
fs.readFile(path[, option], callback)pathoptioncallback// 1. Import fs modular , To manipulate the file
const fs = require('fs')
// 2. call fs.readFile() Method to read the file
// Parameters 1: Read the storage path of the file
// Parameters 2: The encoding format used when reading the file , Generally, it is specified by default utf8
// Parameters 3: Callback function , Get the results of reading failure and success err dataStr
fs.readFile('./files/1.txt', 'utf8', function(err, dataStr) {
// 2.1 Print failed results
// If the read is successful , be err The value of is null
// If the read fails , be err The value of is Error object ,dataStr The value of is undefined
console.log(err)
console.log('-------')
// 2.2 Print successful results
console.log(dataStr)
})
// General logic can be written like this :
fs.readFile('./files/11.txt', 'utf8', function(err, dataStr) {
if (err) {
return console.log(' Failed to read file !' + err.message)
}
console.log(' Read file successful !' + dataStr)
})
fs.writeFile(path, data[, option], callback)pathdataoptioncallbackconst fs = require('fs')
// 2. call fs.writeFile() Method , Write the contents of the file
// Parameters 1: Indicates the storage path of the file
// Parameters 2: Indicates what to write
// Parameters 3: Callback function
fs.writeFile('./files/3.txt', 'ok123', function(err) {
// 2.1 If the file is written successfully , be err The value is equal to the null
// 2.2 If the file fails to write , be err The value of is equal to a Error object
// console.log(err)
// Judge whether the writing is successful
if (err) {
return console.log(' File write failed !' + err.message)
}
console.log(' File written successfully !')
})
console.log(__dirname)
fs.readFile(__dirname + '/files/1.txt', 'utf8', function(err, dataStr) {
if (err) {
return console.log(' Failed to read file !' + err.message)
}
console.log(' Read file successful !' + dataStr)
})
3.path Path module
const path = require("path")
path.join(...paths)- ...paths <string> Sequence of path fragments
- return<string>Be careful : All operations involving path splicing , All use path.join() Methods to deal with . Don't use + String splicing
const path = require('path')
const fs = require('fs')
// Be careful : ../ Will offset the previous path
const pathStr = path.join('/a', '/b/c', '../../', './d', 'e')
console.log(pathStr) // \a\b\d\e
// replace fs.readFile(__dirname + '/files/1.txt', ...)
fs.readFile(path.join(__dirname, './files/1.txt'), 'utf8', function(err, dataStr) {
if (err) {
return console.log(err.message)
}
console.log(dataStr)
})
path.basename(path[, ext])- path <string>Required parameters , A string representing a path
- ext <string>Optional parameters , Represents the file extension
- return <string> The last part of the path
const path = require('path')
// Define the storage path of the file
const fpath = '/a/b/c/index.html'
const fullName = path.basename(fpath)
console.log(fullName) // index.html
const nameWithoutExt = path.basename(fpath, '.html')
console.log(nameWithoutExt) // index
path.extname(path)- path <string> Required parameters , A string representing a path
- return <string> Return the obtained extension string
const path = require('path')
// This is the storage path of the file
const fpath = '/a/b/c/index.html'
const fext = path.extname(fpath)
console.log(fext)// Output .html
边栏推荐
- Use float to realize left, middle and right layout, and the middle content is adaptive
- 一笔画问题(中国邮递员问题)
- Panorama of volcanic engine cloud growth plan: 30 + plans come out together, and military development advantage areas
- 12-GuliMall 后台管理中商品系统的品牌管理
- Dimension disaster dimension disaster suspense
- [typescript] typescript common types (Part 1)
- 【上位机教程】CANopen通信下一体化步进电机与台达PLC(AS228T)的应用
- 【花雕动手做】有趣好玩的音乐可视化系列小项目(12)---米管快速节奏灯
- One stroke problem (Chinese postman problem)
- Extra (5) - MySQL execution plan (51)
猜你喜欢
2022 employment season! Adobe helps creative industry workers break through the shackles of skills and return to the source of ability

Today in history: IBM obtained the first patent; Verizon acquires Yahoo; Amazon releases fire phone

Kubernetes Flannel:HOST-GW模式
Exploration on cache design optimization of community like business

解决远程主机无法连接mysql数据库的问题

flutter多渠道打包运行

【花雕动手做】有趣好玩的音乐可视化系列小项目(13)---有机棒立柱灯
![[typescript] typescript common types (Part 1)](/img/80/5c8c51b92d3a9d76f38beba7be0aa6.png)
[typescript] typescript common types (Part 1)

从其他文件触发pytest.main()注意事项

AI-理论-知识图谱1-基础
随机推荐
解决远程主机无法连接mysql数据库的问题
Qualcomm once again "bet" on Zhongke Chuangda to challenge the full stack solution of intelligent driving software and hardware
【花雕动手做】有趣好玩的音乐可视化系列小项目(12)---米管快速节奏灯
[upper computer tutorial] Application of integrated stepping motor and Delta PLC (as228t) under CANopen communication
The parent component accesses the methods or parameters of the child component (the child component exposes the method defineexpose)
【TypeScript】TypeScript常用类型(上篇)
C#把Type当做泛型T,来作为方法的泛型进行使用
Use positioning to realize left, middle and right layout, and the middle content is adaptive
Kubernetes - Introduction to PV and PVC of advanced storage
StreamNative 团队文化:一家“透明”的公司
1-6月中国ADAS供应商占比9% 又一家零部件巨头全面布局智驾新赛道
Sword finger offer (21): push in and pop-up sequence of stack
JSON格式执行计划(6)—mysql执行计划(五十二)
同站攻击(相关域攻击)论文阅读 Can I Take Your Subdomain?Exploring Same-Site Attacks in the Modern Web
Reflection, an implementation of automatic repeated call interface
B+树索引使用(9)分组、回表、覆盖索引(二十一)
Solution 5g technology helps build smart Parks
Emotion analysis model based on Bert
Extra(5)—mysql执行计划(五十一)
Leetcode 217. there are duplicate elements