当前位置:网站首页>Nodejs file module FS
Nodejs file module FS
2022-06-13 07:19:00 【Bug pill】
File module fs
Buffer( buffer )
It means in V8 JavaScript A fixed size memory block allocated outside the engine
It's like an array ; Arrays cannot be used to store binary files ,Buffer It is specially used to store binary files
Use Buffer There is no need to introduce modules , It can be used directly
stay buffer All the data stored in is binary data , But on display , It's all about 16 Base display ,2 Base too long
Buffer Once the size is determined , Can't modify , It is actually a direct operation on the underlying memory
buffer An element in , One byte of memory
8bit =1byte ( byte )
1024byte = 1kb
1024kb =1mb
1024mb =1gb
1024gb =1tb
One letter takes one byte , A Chinese word occupies 3 Bytes
Basic grammar
let buf=Buffer.from(str) // Convert string to buffer
buf.length // buf How many bytes
Buffer.alloc(size) // Create a... Of a specified size Buffer
Buffer.allocUnsafe(size) // Create a... Of a specified size Buffer, But there may be sensitive data , Allocate a continuous space , But the original data will not be cleared
buf.toString() // take buffer To string
Writing files
The essence of the server is to send local files to remote clients ;fs All operations in the module are available in two forms : Synchronous and asynchronous
Synchronizing the file system will block the execution of the program , Asynchronous will not , When the operation is completed , Return the result through the callback function
Write synchronization file
1》 Open file
fs.openSync(path,flags [, mode] )
path: The file path to open
flags: The type of operation required to open a file
| Pattern | explain | |
|---|---|---|
| r | Read the file , An exception occurs if the file does not exist | |
| w | Open file for write operation ( Will be covered ), If the file does not exist, it will create , If it exists, the content will be overwritten | |
| a | Open the file for appending , If there is no file, create |
mode: Set the operation permission of the file , General non transmission
2》 Like writing content in a file
A file descriptor will be returned as a result , We can perform various operations on files through file descriptors
const fd= fs.writeSync(fd,string [,position, endoding])
fd: The descriptor of the file
string: What to write
positioin: Start of write
encoding: The encoding of the write , The default is utf-8
3》 Save and close file
fs.closeSync(fd)
fs It's the core module , No need to download , Direct introduction and use
var fs = require("fs");
var fd = fs.openSync("hello.txt", "w");
fs.writeSync(fd, " love you ");
fs.closeSync(fd);
Asynchronous file writing
Basic steps : open – write in – close
fs.open(path,flags [,mode ], callback)
The callback function takes two arguments :err: Error object , Otherwise null , fd File descriptor
fs.write(fd,string [,position, endoding] , callback)
fs.close()
const fs = require("fs");
fs.open("hello2.txt", "w", function (err, fd) {
// console.log(arguments);
if (!err) {
fs.write(fd, " I love you too - asynchronous ", function (err) {
if (err) {
console.log(err);
}
fs.close(fd, function (err) {
if (!err) {
console.log(" File closed successfully ");
}
});
});
} else {
console.log(err);
}
});
Simple file write
asynchronous :
fs.writeFile(filePath,dataContent, [, options] , callback)
filePath: Write file path
dataContent: Written content 、 data
options optional { encoding: Default utf-8, mode: Default 0o666, flag: Default w }
callback Callback function
const fs = require("fs");
fs.writeFile("simple.txt", " Simple asynchronous file operation ", function (err) {
if (!err) {
console.log(" Write successfully ");
}
});
Sync
fs.writeFileSync(filePath,dataContent, [, options] )
Writing of streaming file
Create a streaming file
fs.createWriteStream(path [, options])
path: Operation file path
Simple stream writes :
const fs = require("fs");
// Create stream
const ws = fs.createWriteStream("stream.txt");
// Listen for the opening and closing of the stream , Only open and close once , So I used once
ws.once("open", function () {
console.log(" The stream opens ");
});
ws.once("close", function () {
console.log(" The stream is closed ");
});
// Write content , adopt ws Input
ws.write(" Hoe standing grain gradually pawning a midday ;");
ws.write(" Learning depends on autonomy ;");
ws.write(" It's hard work ;");
ws.write(" Like a nanny ;");
// Closed flow
ws.end();
File reading
Simple file reading
asynchronous :
fs.readFile(path [,options], callback)
The return is buffer
const fs = require("fs");
fs.readFile("./hello.txt", function (err, data) {
if (!err) {
// The return is buffer Data of type , Because what you read is not necessarily a string , So you can't directly return a string
console.log(data);
console.log(data.toString());
}
});
Sync :
const data=fs.readFileSync(path [,options])
Reading of streaming file
Streaming file reading is also suitable for some larger files , You can read files into memory several times
fs.createReadStream(path[, options])
Read the data in the readable stream , You need to bind a for the readable stream data event , After binding, it will automatically start reading data , The readable stream will be automatically closed after reading
What I read is buffer data
const fs = require("fs");
const rs = fs.createReadStream("./stream.txt");
rs.once("open", function () {
console.log(" The readable stream opens ");
});
rs.once("close", function () {
console.log(" The readable stream is closed ");
});
rs.on("data", function (data) {
console.log(data); // buffer
});
Put the read stream into another file
const fs = require("fs");
const rs = fs.createReadStream("./stream.txt");
const ws = fs.createWriteStream("./copyStream.txt");
rs.once("close", function () {
console.log(" The readable stream is closed ");
ws.end();
});
rs.on("data", function (data) {
ws.write(data);
});
pipe You can output the contents of a readable stream directly to a writable stream
const fs = require("fs");
const rs = fs.createReadStream("./bgc.jpg");
const ws = fs.createWriteStream("./copyBgc.jpg");
rs.pipe(ws);
Other operating
Verify that the path exists
const isExist=fs.existsSync(path)
Get file information
fs.stat(path,callback)
fs.statSync(path)
const fs = require("fs");
fs.stat("./hello.txt", function (err, Stats) {
if (!err) {
console.log(Stats);
}
});
Delete file
fs.unlink(path,callback)
fs.unlinkSync(path)
Lists the files
Returns an array of strings
fs.readdir(path [, options] ,callback)
fs.readdirSync(path [,options])
truncate file
truncate file , Change the file to the specified size ( byte )
fs.truncate(path,len,callback)
fs.truncateSync(path,len)
fs.truncateSync(“./hello2.txt”, 100)
Without so many bytes, he would spell null; If a Chinese character is not truncated , Cut it in half and you won't recognize it , Is to show a diamond to say hello
Build directory
fs.mddir(path [,mode],callback)
fs.mddirSync(path [,mode])
Delete directory
fs.rmdir(path,callback)
fs.rmdirSync(path)
Rename files and directories
fs.rename(oldPath,newPath,callback)
fs.renameSync(oldPath,newPath)
Watch me see change write
fs.watchFile(filename [,options] , lintenerFunc)
options There's an attribute in interval : How often is it updated , The default value is 5007
fs.watchFile("./hello.txt", function (cur, pre) {
console.log(cur.size, pre.size);
});
Read more official documentation :http://nodejs.cn/api/
边栏推荐
- 【硬记】脏读、不可重复读、幻读场景核心区别
- 全志V3S环境编译开发流程
- 考研英语
- RT-Thread 模拟器 simulator LVGL控件:button 按钮事件
- Un des backtraders du cadre de quantification lit l'analyseur
- The biggest highlight of wwdc2022: metalfx
- 关于oracle的函数。
- redis-6. Redis master-slave replication, cap, Paxos, cluster sharding cluster 01
- [hard copy] core differences among dirty reading, non repeatable reading and unreal reading scenarios
- 同花顺可以开股票账户吗?安全吗?
猜你喜欢

redis-3. Redis list, set, hash, sorted_ set、skiplist

基于ESP32CAM实现WebSocket服务器实时点灯

微隔离(MSG)

FSM state machine

Implementation of fruit mall wholesale platform based on SSM

Application of DS18B20 temperature sensor based on FPGA

关于#数据库#的问题:PGADMIN4 编辑sql窗口问题
![[Markov chain Monte Carlo] Markov chain Monte Carlo method sampling prior distribution](/img/8a/e6423168e110a168bc3cc6407628f6.png)
[Markov chain Monte Carlo] Markov chain Monte Carlo method sampling prior distribution

学习Mysql基础第一天

SDN basic overview
随机推荐
Tidb server tuning
Implementation of fruit mall wholesale platform based on SSM
Is it safe for Hangzhou Securities to open an account?
How to stop PHP FPM service in php7
Real time lighting of websocket server based on esp32cam
Tidb statistics
Tidb index optimization
redis-3. Redis list, set, hash, sorted_ set、skiplist
Table access among Oracle database users
ISIS的vsys(虚拟系统)
玄武云科技通过上市聆讯:业绩波动明显,陈永辉等三人为控股股东
oracle问题,字段里面的数据被逗号隔开,取逗号两边数据
2022 - 06 - 12: dans un échiquier carré n * N, il y a n * n pièces, donc chaque pièce peut avoir exactement une pièce. Mais maintenant quelques pièces sont rassemblées sur une grille, par exemple: 2 0
[turn to] FPGA interview questions
【转】FPGA面试题
Ticdc introduction
[vivefocus uses the wavevr plug-in to obtain handle operation events]
理財產品連續幾天收益都是零是怎麼回事?
How to write an amazing design document?
Interview questions must be asked - Optimization of large table Pagination