当前位置:网站首页>05_ Node JS file management module FS
05_ Node JS file management module FS
2022-06-30 10:39:00 【Full stack programmer webmaster】
One 、fs Basic method :
- fs.stat Check whether it's a file or a directory .
- fs.mkdir Create directory .
- fs.writeFile Create write file .
- fs.appendFile Additional documents .
- fs.readFile Read the file ( asynchronous ).
- fs.readFileSync Read the file ( Sync ).
- fs.readdir Read directory .
- fs.rename rename .
- fs.rmdir Delete directory .
- fs.unlink Delete file .
1、fs.stat: Check whether it's a file or a directory
fs.js
const fs = require("fs");
fs.stat('fs.js', (error, stats) => {
if (error) {
console.log(error);
return false;
} else {
console.log(stats);
console.log(` file :${stats.isFile()}`); // file :true
console.log(` Catalog :${stats.isDirectory()}`); // Catalog :false
return false;
};
});
Copy code perform node fs.js.
console.log(stats):
{ dev: 636204,
mode: 33206,
nlink: 1,
uid: 0,
gid: 0,
rdev: 0,
blksize: undefined,
ino: 1407374883609714,
size: 242,
blocks: undefined,
atime: 2018-12-25T09:14:40.866Z,
mtime: 2019-01-15T09:18:06.561Z,
ctime: 2019-01-15T09:18:06.561Z,
birthtime: 2018-12-25T09:14:40.866Z }
console.log(` file :${stats.isFile()}`); // file :true
console.log(` Catalog :${stats.isDirectory()}`); // Catalog :false
Copy code Add :
- stats.isFile() If it's a file return true, Otherwise return to false.
- stats.isDirectory() If it's a directory return true, Otherwise return to false.
- stats.isBlockDevice() If it's block device return true, Otherwise return to false.
- stats.isCharacterDevice() If it's character device return true, Otherwise return to false.
- stats.isSymbolicLink() If it's a soft link back true, Otherwise return to false.
- stats.isFIFO() If it is FIFO, return true, Otherwise return to false,FIFO yes UNIX A special type of command pipeline in .
- stats.isSocket() If it is Socket return true, Otherwise return to false.
2、fs.mkdir: Create directory
fs.js
const fs = require("fs");
fs.mkdir('images', (err) => {
if (err) {
console.log(err);
return false;
} else {
console.log(" Directory created successfully !");
};
});
Copy code Receiving parameters :
- path: Directory path to be created .
- mode: The directory permissions ( read-write permission ), Default 0777.
- callback: Callback , Pass exception parameters err.
perform node fs.js.
You'll find one more in the directory images Folder .
3、fs.rmdir: Delete directory
fs.js
const fs = require("fs");
fs.rmdir('images', (err) => {
if (err) {
console.log(err);
return false;
} else {
console.log(" Directory deleted successfully !");
};
});
Copy code perform node fs.js.
You will find the directory images Folder deleted .
4、fs.writeFile: Create write file
fs.js
const fs = require("fs");
fs.writeFile("index.js", "hello NodeJS!", (err) => {
if (err) {
console.log(err);
return false;
} else {
console.log(" File written successfully !");
};
});
Copy code Receiving parameters :
- filename (String) File name .
- data (String | Buffer) What will be written , It can be a string or buffer data .
- encoding (String) Optional . Default ‘utf-8’, When data yes buffer when , The value should be ignored.
- mode (Number) File read and write permissions , Default 438.
- flag (String) The default value is ‘w’.
- callback { Function } Callback , Pass an exception parameter err.
perform node fs.js.
You'll find one more in the directory index.js Folder , And added “hello NodeJS!” The content of .
Be careful , Such writes , Is to clear all data in the original file , Then add “hello NodeJS!” this sentence , namely : Existence is coverage , Create... If it doesn't exist .
5、fs.unlink: Delete file
fs.js
const fs = require("fs");
fs.unlink("index.js", (err) => {
if (err) {
console.log(err);
return false;
} else {
console.log(" Delete successful !");
};
});
Copy code perform node fs.js.
You will find the directory index.js File deleted .
6、fs.appendFile: Additional documents
fs.js
const fs = require("fs");
fs.appendFile("index.js", " Additional content ", (err) => {
if (err) {
console.log(err);
return false;
} else {
console.log(" Append succeeded !");
};
});
Copy code perform node fs.js.
You will find the directory index.js A paragraph was appended to the document “ Additional content ”.
7、fs.readFile: Read the file
fs.js
const fs = require("fs");
fs.readFile("index.js", (err, data) => {
if (err) {
console.log(err);
return false;
} else {
console.log(" Read file successful !");
console.log(data); // <Buffer 68 65 6c 6c 6f 20 4e 6f 64 65 4a 53 ef bc 81 e8 bf bd e5 8a a0 e7 9a 84 e5 86 85 e5 ae b9>
};
});
Copy code perform node fs.js.
console.log(data) Print the results :
<Buffer 68 65 6c 6c 6f 20 4e 6f 64 65 4a 53 ef bc 81 e8 bf bd e5 8a a0 e7 9a 84 e5 86 85 e5 ae b9>
Copy code 8、fs.readdir: Read directory
fs.js
const fs = require("fs");
fs.readdir("node_modules", (err, data) => {
if (err) {
console.log(err);
return false;
} else {
console.log(" Reading directory succeeded !");
console.log(data); // [ '03_tool_multiply.js', 'my_module' ]
};
});
Copy code perform node fs.js.
console.log(data) Print the results :
[ '03_tool_multiply.js', 'my_module' ]
Copy code 9、fs.rename: rename
fs.js
const fs = require("fs");
fs.rename("index.js", "new_index.js", (err) => {
if (err) {
console.log(err);
return false;
} else {
console.log(" Rename successful !");
};
});
Copy code perform node fs.js.
You will find the directory index.js The file was modified to new_index.js.
10、 Add :fs.rename You can also cut
fs.js
const fs = require("fs");
fs.rename("new_index.js", "node_modules/new_index.js", (err) => {
if (err) {
console.log(err);
return false;
} else {
console.log(" Cut successfully !");
};
});
Copy code perform node fs.js.
You will find the directory new_index.js The file was moved to node_modules Under the table of contents .
Two 、fs Case study
1、 To determine if there is upload Catalog
fsDemo.js
const fs = require("fs");
fs.stat("upload", (err, stats) => {
if (err) {
// without , establish upload Catalog
fs.mkdir("upload", (err) => {
if (err) {
console.log(err);
return false;
} else {
console.log(" Create success !");
};
})
} else {
console.log(stats.isDirectory()); // true
console.log(" Yes upload Catalog , You can do more !");
};
});
Copy code perform fsDemo.js.
Print the results :
console.log(stats.isDirectory()); // true
Yes upload Catalog , You can do more !
Copy code 2、 Read all the files in the directory
fsDemo.js
const fs = require("fs");
fs.readdir("../05fs/", (err, files) => {
if (err) {
console.log(err);
return false;
} else {
console.log(files);
let filesArr = [];
(function getFile(i) {
// The loop ends
if (i == files.length) {
// Print out all directories
console.log(" Catalog ");
console.log(filesArr);
return false;
};
// Determine whether the directory is a file or a folder
fs.stat("../05fs/" + files[i], (err, stats) => {
if (stats.isDirectory()) {
filesArr.push(files[i]);
};
// Recursively call
getFile(i + 1);
});
})(0);
};
});
Copy code perform fsDemo.js.
Print the results :
[ 'fs.js', 'fsDemo.js', 'fsStream.js', 'upload' ]
Catalog
[ 'upload' ]
Copy code 3、 ... and 、fs flow
1、fs Stream and its reading
First create a index.js file , And add test text .
fsStream.js
const fs = require("fs");
// Read files by stream
const fileReadStream = fs.createReadStream("index.js");
// Number of reads
let count = 0;
// Save the data
let str = "";
// Start reading
fileReadStream.on("data", (chunk) => {
console.log(`${++count} Received :${chunk.length}`);
str += chunk;
});
// Read complete
fileReadStream.on("end", () => {
console.log(" end ");
console.log(count);
console.log(str);
});
// Read failed
fileReadStream.on("err", (err) => {
console.log(err);
});
Copy code perform fsStream.js.
Print the results :
1 Received :18
end
1
fs Stream and its reading
Copy code 2、 Write to stream
fsStream.js
const fs = require("fs");
let data = " In the data ...";
// Create a writable stream , Write to index.js
let fileWriteStream = fs.createWriteStream("index.js");
// Start writing
fileWriteStream.write(data, "utf8");
// Write completion
fileWriteStream.end();
fileWriteStream.on("finish", () => {
console.log(" Write completion !");
});
Copy code perform fsStream.js.
open index.js file , I found that the content inside turned into “ In the data …”.
Print the results :
Write completion !
Copy code Above, we read and write through the stream .
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/101118.html Link to the original text :https://javaforall.cn
边栏推荐
- 技能梳理[email protected]+阿里云+nbiot+dht11+bh1750+土壤湿度传感器+oled
- Questions about cookies and sessions
- 超长干货 | Kubernetes命名空间详解
- “昆明城市咖啡地图”再度开启,咖啡拉近城市距离
- Oracle creates a stored procedure successfully, but the compilation fails
- South China Industrial Group launched digital economy and successfully held the city chain technology conference
- WGet -- 404 not found due to spaces in URL
- MATLAB image histogram equalization, namely spatial filtering
- Get through the supply chain Shenzhen gift show helps cross-border e-commerce find ways to break the situation
- Jinbei LT6 is powerful in the year of the tiger, making waves
猜你喜欢

Basic MySQL operation commands of database

苹果5G芯片被曝研发失败,QQ密码bug引热议,蔚来回应做空传闻,今日更多大新闻在此...

MySQL log management, backup and recovery of databases (2)

Launch of Rural Revitalization public welfare fund and release of public welfare bank for intangible cultural heritage protection of ancient tea tree

Jump table introduction

How to seize the opportunity of NFT's "chaos"?

ArcGIS Pro scripting tool (5) - delete duplicates after sorting

Compétences Comb 27 @ Body sense Manipulator

MATLAB image histogram equalization, namely spatial filtering
[email protected] somatosensory manipulator"/>Skill combing [email protected] somatosensory manipulator
随机推荐
Splendid China: public welfare tourism for the middle-aged and the elderly - entering Foshan nursing home
Go -- maximum heap and minimum heap
Overview of currency
Xinguan has no lover, and all the people benefit from loving deeds to warm the world -- donation to the public welfare action of Shangqiu children's welfare home
Questions about cookies and sessions
敏捷开发: 超级易用水桶估计系统
"Kunming City coffee map" activity was launched again
The digital collection of sunanmin's lotus heart clearing was launched on the Great Wall Digital Art
"Kunming City coffee map" activity was launched again
最新SCI影响因子公布:国产期刊最高破46分!网友:算是把IF玩明白了
The famous painter shiguoliang's "harvest season" digital collection was launched on the Great Wall Digital Art
程序员需知的 59 个网站
半钢同轴射频线的史密斯圆图查看和网络分析仪E5071C的射频线匹配校准
【Rust日报】2021-01-22 首份Rust月刊杂志邀请大家一起参与
透過華為軍團看科技之變(五):智慧園區
Gd32 RT thread DAC driver function
GeoffreyHinton:我的五十年深度学习生涯与研究心法
Great Wall digital art digital collection platform releases the creation Badge
技能梳理[email protected]在oled上控制一条狗的奔跑
Action bright: take good care of children's eyes together -- a summary of the field investigation on the implementation of action bright in Guangxi