当前位置:网站首页>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/
边栏推荐
- redis-2. Redis string type & bitmap
- How to solve the 404 problem
- . Net code to implement get request and post request
- Word document export
- A solution to the problem that there is always a newline character when C merges multiple RichTextBox contents
- Deploy RDS service
- Lightning breakpoint continuation
- 怎么写出一份令人惊叹的设计文档?
- JMeter encryption interface test
- 10 Honest Facts I Want To Share With All Junior Developers
猜你喜欢
powerdisgner逆向生成oracle数据模型
Lightning breakpoint continuation
Implementation of fruit mall wholesale platform based on SSM
RT thread simulator lvgl control: switch switch button control
C#合并多个richtextbox内容时始终存在换行符的解决方法
Tidb index optimization
redis-5. Redis' RDB, fork, copyonwrite, AOF, RDB & AOF are mixed
Tidb statistics
简单了解C语言基本语
redis-2. Redis string type & bitmap
随机推荐
C # related knowledge points
RT-Thread 模拟器 simulator LVGL控件:switch 开关按钮控件
杭州网上开户是安全的吗?
RT thread simulator lvgl control: switch switch button control
c#高级编程-特性篇
redis-1. Install redis with pictures and texts
Try to use renderdoc to view the shader code of UE
号称下一代监控系统 来看看它有多牛逼
Compilation and development process of Quanzhi v3s environment
考研英语
FSM状态机
关于#数据库#的问题:PGADMIN4 编辑sql窗口问题
Table access among Oracle database users
Calculate running total / running balance
Simple understanding of basic language of C language
尝试使用RenderDoc查看UE的Shader代码
【微弱瞬态信号检测】混沌背景下微弱瞬态信号的SVM检测方法的matlab仿真
Can flush open a stock account? Is it safe?
Issues related to C # delegation and events
June 12, 2022: if there are n*n pieces in an n*n square chessboard, each grid can have exactly one piece. But now some pieces are gathered on a grid, such as 2030100300. The above two-dimensional arra