当前位置:网站首页>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
边栏推荐
- "Kunming City coffee map" activity was launched again
- MySQL advanced SQL statement of database (1)
- Basic MySQL operation commands of database
- Getting started with X86 - take over bare metal control
- Go -- maximum heap and minimum heap
- CSDN博客运营团队2022年H1总结
- Who should the newly admitted miners bow to in front of the chip machine and the graphics card machine
- ArcGIS Pro + PS 矢量化用地规划图
- 透过华为军团看科技之变(五):智慧园区
- Arm新CPU性能提升22%,最高可组合12核,GPU首配硬件光追,网友:跟苹果的差距越来越大了...
猜你喜欢

KOREANO ESSENTIAL打造气质职场范
[email protected]在oled上控制一条狗的奔跑"/>技能梳理[email protected]在oled上控制一条狗的奔跑

那个程序员,被打了。

MySQL index, transaction and storage engine of database (3)

The famous painter shiguoliang's "harvest season" digital collection was launched on the Great Wall Digital Art

Test memory read rate

Yixian e-commerce released its first quarterly report: adhere to R & D and brand investment to achieve sustainable and high-quality development

Splendid China: public welfare tourism for the middle-aged and the elderly - entering Foshan nursing home

历史上的今天:微软收购 PowerPoint 开发商;SGI 和 MIPS 合并

Using LVM to resize partitions
随机推荐
GD32 RT-Thread flash驱动函数
Eth is not connected to the ore pool
Gd32 RT thread ota/bootloader driver function
mysql数据库基础:存储过程和函数
R语言aov函数进行重复测量方差分析(Repeated measures ANOVA、其中一个组内因素和一个组间因素)、分别使用interaction.plot函数和boxplot对交互作用进行可视化
MySQL index, transaction and storage engine of database (2)
Yixian e-commerce released its first quarterly report: adhere to R & D and brand investment to achieve sustainable and high-quality development
ArcGIS Pro脚本工具(5)——排序后删除重复项
那个程序员,被打了。
Voir le changement technologique à travers la Légion Huawei (5): Smart Park
透過華為軍團看科技之變(五):智慧園區
Skill combing [email protected] intelligent instrument teaching aids based on 51 series single chip microcomputer
机器学习面试准备(一)KNN
我在鹅厂淘到了一波“炼丹神器”,开发者快打包
Chen Haotian won the national championship of the national finals of the 7th children's model star ceremony
KOREANO ESSENTIAL打造气质职场范
郭琳加冕 2022第三季完美大师 全球人气季军
ArcGIS Pro scripting tool (5) - delete duplicates after sorting
ArcGIS PRO + PS vectorized land use planning map
"Kunming City coffee map" activity was launched again