当前位置:网站首页>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/

原网站

版权声明
本文为[Bug pill]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/164/202206130715038268.html