当前位置:网站首页>Node (II)
Node (II)
2022-07-29 09:40:00 【Front grass seed】
Catalog
1. fs.readFile(); Read the file
2.fs.writeFile(path ,data,callback(err)) write file ( create a file )
3.fs.unlink(path,callback(err)) Delete file
4.fs.appendFile(path, data, callback(el)) Write the file as an append
6.fs.rename(oldPath, newPath, callback);
7.fs.copyFile(oldPath, newPath, callback); Copy files
8.fs.readdir(path,callback(el))
6.questring modular and Each module implements static resource hosting
9. Static resource hosting ( Relative paths )
10. Loading process of web pages
1. __dirname and __filename
1. They save strings
2.__dirname Current js file directory ( It's the address , character string ): Absolute path Folder (directory)
__filename Current js file The catalog of ( It's the address , character string ): Absolute path
verification :
console.log(11111111,__dirname,222222222);
console.log(33333333,__filename,4444444);
Be careful :fs.readFile(), Access a specific file , Not the directory where a file is located .
So it should be written like this :
var fs = require('fs');
fs.readFile(__dirname + '/index.html',(err,data)=>{
console.log(err,data.toString());
});Instead of just writing fs.readFile(__dirname,(err,data)=>{ }
fs.readFile() Successful visit , Returns the buffer( It's a kind of object ) Binary code

null yes err Value ,data It is returned successfully after accessing the file buffer Binary code . Can be converted to character string
console.log(err,data.toString());The result is :

This is fs.readFile() The one you visited index.html file .
2. Static website
1. Front end input URL , Access back end
var http = require('http');
var fs = require('fs');
var app = http.createServer((req,res)=>{
// The purpose of writing a print function here : It is convenient to see which Network request
console.log(req.url);
if(req.url == '/index.html'){
fs.readFile(__dirname + '/index.html',(err,data)=>{
res.end(data.toString());
});
}
});
app.listen(8081);Be careful : Take the above function as an example : After the browser enters the address , You don't just ask for web pages and pictures , After the browser enters the web address , Just asked for index.html This file goes to the user's computer , Then the user's computer starts running index.html The code in this file , Then run the code , encounter scr,href Such as these , Then make the network request again , It's not always asking .
var http = require('http');
var fs = require('fs');
var app = http.createServer((req, res) => {
// The purpose of writing a print function here : It is convenient to see which Network request
console.log(req.url);
if (req.url == '/index.html') {
fs.readFile(__dirname + '/index.html', (err, data) => {
res.end(data);
});
}
// Will spontaneously request small icons '/favicon.ico'
else if (req.url == '/favicon.ico') {
fs.readFile(__dirname + '/daimeng.ico', (err, data) => {
res.end(data);
});
}
});
app.listen(8081);Abbreviation :( important )
var http = require('http');
var fs = require('fs');
var app = http.createServer((req, res) => {
// The purpose of writing a print function here : It is convenient to see which Network request
console.log(req.url);
fs.readFile(__dirname + req.url ,(err,data)=>{
res.end(data);
})
});
app.listen(8081);3.fs modular
node.js in , Put a series of functions of the same type Encapsulated in the same module It's modularity .
fs modular : Modules that operate on files .
1. fs.readFile(); Read the file
var fs = require('fs');
var path = __dirname + "/js/index.html"
fs.readFile(path,(err,data)=>{
console.log(err,data);
})among :path: Is the path where the file is read . err: Reading failure returns a value ,data: Read successfully and return buffer Binary code , Can be converted to string encoding data.toString();
2.fs.writeFile(path ,data,callback(err)) write file ( create a file )
fs.writeFile(path ,data,callback(err)) If the file exists , The contents written by this method will cover the contents of the old file , Create a new file if it doesn't exist .
path - File path data - Data to write to file , It can be String( character string )
callback - Callback function , The callback function contains only error message parameters (err), Returns... On write failure . Write successfully ,err There's no data , Write failure ,err There's data .
var fs = require('fs');
var path = __dirname + "/js/a.txt"
fs.writeFile(path,'helloa',function(err){
console.log(err);
})Before the program runs :a.txt In the file :

After program running :
console.log(err); return null Represents that the program is written successfully


Be careful : To create a file, you can only create a file under an existing folder , If a folder does not exist , It is impossible to create files in this folder , Will report a mistake .

3.fs.unlink(path,callback(err)) Delete file
path - File path .
callback(err) - Delete callback function , If deletion fails ,err Return the reason for deletion failure . Delete successful , Then return to null
If the deletion fails : Either the file does not exist , Or the permission is not enough .
var fs = require('fs');
var path = __dirname + "/js/new.txt"
fs.unlink(path,function(err){
console.log(err);
})4.fs.appendFile(path, data, callback(el)) Write the file as an append
Splice content into files .
If you splice content into a file , This file does not exist , It creates a .
var fs = require('fs');
var path = __dirname + "/js/a.txt"
fs.appendFile(path,' I'm an addition ',function(el){
console.log(el); //null
})Append succeeded , The callback prints out null

5.fs.mkdir() Create a folder
var fs = require('fs');
var path = __dirname + "/js/test"
fs.mkdir(path,(err)=>{
console.log(err);
})Create a folder : The folder name is test
6.fs.rename(oldPath, newPath, callback);
Move / Rename a file or directory : The whole function is equivalent to renaming a file / Folder path
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
7.fs.copyFile(oldPath, newPath, callback); Copy files
fs.copyFile(oldPath, newPath, callback);
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
After copying files, both files will be stored on disk , If you want to delete , call fs.unlink(oldpath)
var fs = require('fs');
var oldpath = __dirname + '/js/a.txt'
var newpath = __dirname + '/js/test/a'
fs.copyFile(oldpath,newpath,(err)=>{
fs.unlink(oldpath,()=>{})
})8.fs.readdir(path,callback(el))

4. website URL
How to write a website :
https://passport2.chaoxing.com/login?fid=&newversion=true#top1meaning :

Browser enter web address , except # Later It won't be sent to backstage , The front will happen to the backstage .
domain name : ==》DNS analysis Will resolve the domain name into a id port
5.url modular
// Analysis website rul Related functions modular
var url = require('url');1.url.parse( website )
Role is : Put a website ( The URL is a string , Put it in quotation marks ) Parse into an object
var url = require('url');
var str = 'https://passport2.chaoxing.com/login?fid=&newversion=true#top1'
var obj = url.parse(str);
console.log(obj);
protocol : agreement
host/hostname: host ( domain name )
query(querystring): Inquire about (? after ,# Before no. )
pathname:( Domain name behind / , until ? Previous content ) . This is very important , Static resource hosting requires
url Module use :
// website :https:/ip:port/login?fid=&newversion=true#top1
var http = requrie('http');
var fs = require('fs');
var app = http.createServer((req,res)=>{
console.log(req.url); // here req.url Express :/login?fid=&newversion=true#top1
fs.readFile(__dirname + req.url,(err,data)=>{
res.end(data)
})
})If the URL entered in the front end is :https://ip:port/login?fid=&newversion=true#top1, So the req.rul Namely :/login?fid=&newversion=true#top1, Until then fs.readFile Inside :__dirname + req.url There will be more in the address ?fid=&newversion=true#top1 This part , The file under the corresponding path cannot be read . So go through url.parse Method , Cut out unused string fragments :
// website :https://ip:port/login?fid=&newversion=true#top1
var http = requrie('http');
var fs = require('fs');
const { url } = require('inspector');
var app = http.createServer((req,res)=>{
console.log(req.url); // here req.url Express :/login?fid=&newversion=true#top1
var path = url.parse(req.url).pathname; //path = /login
fs.readFile(__dirname + path,(err,data)=>{
res.end(data)
})
})commonly : The website sent by the user , Usually with parameters (eg:?fid=&newversion=true#top1), When we read the file , These parameters are not required , Only when doing business , So when reading files, use url.parse Method cuts out unused parameters .
6.questring modular and Each module implements static resource hosting
7.mime modular
8. All kinds of paths
9. Static resource hosting ( Relative paths )
10. Loading process of web pages
边栏推荐
- 简述堆和栈的区别
- User identity identification and account system practice
- 【C语言】扫雷(递归展开 + 标记功能)
- (Video + graphics) introduction to machine learning series - Chapter 1 Introduction
- 怎么样的框架对于开发者是友好的?
- Sublime Text3 set different indents for different files
- 怎样查询快递物流筛选出无信息单号删除或者复制
- mysql 数据库 期末复习题库
- redis可视化工具读取数据乱码问题解决
- 分布式Session共享的4类技术方案,与优劣势比较
猜你喜欢

上海交大牵手淘宝成立媒体计算实验室:推动视频超分等关键技术发展

Sample is new and supported from API 8! Come and take it

Floweable foundation Chapter 1

Excel tool for generating database table structure

Custom configuration

redis可视化工具读取数据乱码问题解决

Youboxun, the gold donor of the open atom open source foundation, joined hands with partners to help openharmony break the circle!

WebAssembly 2022 问卷调查结果新鲜出炉

Axurerp prototype design starts quickly
![[machine learning] logistic regression code exercise](/img/dc/203f240e2eb213dbd6173d17e47ec6.jpg)
[machine learning] logistic regression code exercise
随机推荐
【BERT-多标签文本分类实战】之一——实战项目总览
Anfulai embedded weekly report no. 273: 2022.07.04--2022.07.10
How to query express logistics and filter out no information doc No. to delete or copy
基于C语言实现的NFA确定化和DFA最小化
Floweable foundation Chapter 1
div 水平排列
vector实现
开放原子开源基金会黄金捐赠人优博讯携手合作伙伴,助力OpenHarmony破圈!
RTMP supports h265 streaming
Unity xchart3.0 basic usage quick start
MySQL的数据类型
Shutter -- use camera (continuously updating)
Opencv introductory basic learning
如何为OpenHarmony做贡献
Mysql database final review question bank
C语言的传参方式(int x)(int *x)(int &x)
基于ArkUI eTS开发的坚果新闻(NutNews)
NFA determination and DFA minimization based on C language
Zhongang Mining: four steps for sustainable and healthy development of fluorite industry
SiC Power Semiconductor Industry Summit Forum successfully held