When talking about Stream/Buffer, we have already started using require("fs")
to introduce files The module does some operations
The file module is an encapsulation of underlying file operations, such as file reading and writing/opening and closing/delete adding, etc.
The biggest feature of the file module is that all methods are provided There are two versions of Synchronous and Asynchronous . Methods with sync suffix are all synchronous methods, and those without are all asynchronous methods
File common sense
File Permissions
Because you need to operate the file, you need to set the corresponding permissions. [Related tutorial recommendations: nodejs video tutorial, Programming teaching]
is mainly divided into three roles, file owner, The group to which the file belongs and other users
File permissions are divided into read, write, and execute. The numbers are expressed as 4/2/1 respectively. When there is no permission, it is expressed as 0
If execution is canceled Permissions mean that no files in the folder can be accessed, and you cannot cd to the folder
Use Linux commandsll
You can check the permissions of the files/folders in the directory
The first d represents the folder, - represents the file, followed by the file permissions // TODO: What does @ represent
File identification
In Node, the identification bit represents the operation mode of the file, readable/writable/readable and writable, etc., which can be arranged and combined
File descriptor
As mentioned in the previous content, the operating system will assign a numerical identifier called a file descriptor to each open file, and use these values ????to track specific document.
File descriptors generally start from 3, 0/1/2 represent standard input/standard output/error output respectively
Commonly used API
Some practices
Filtering the appropriate files in your project
const fs = require("fs"); const path = require("path"); const { promisify } = require("util"); const reg = new RegExp("(.ts[x]*|.js[x]*|.json)$"); const targetPath = path.resolve(__dirname, "../mini-proxy-mobx"); const readDir = (targetPath, callback) => { fs.readdir(targetPath, (err, files) => { if (err) callback(err); files.forEach(async (file) => { const filePath = path.resolve(__dirname, `${targetPath}/${file}`); const stats = await promisify(fs.stat)(filePath); if (stats.isDirectory()) { await readDir(filePath); } else { checkFile(filePath); } }); }); }; const checkFile = (file) => { if (reg.test(file)) { console.log(file); } }; readDir(targetPath, (err) => { throw err; });
File copy
Problem: Need to copy the contents of file 1 to file 2
File API
You can use fs.readFile to read the file content, and then use fs.writeFile to write a new file
const fs = require("fs"); const path = require("path"); const sourceFile = path.resolve(__dirname, "../doc/Mobx原理及丐版實現(xiàn).md"); const targetFile = path.resolve(__dirname, "target.txt"); fs.readFile(sourceFile, (err, data) => { if (err) throw err; const dataStr = data.toString(); fs.writeFile(targetFile, dataStr, (err) => { if (err) throw err; console.log("copy success~"); process.exit(1); }); });
? Is there any problem with this? As we said in Stream, it requires a Click a little bit, otherwise the memory will be overwhelmed when the file is large.
Buffer Use
Use the fs.open method to open the file, obtain the file descriptor, and then call the fs.read/fs.write method to read and write to a specific location. Amount of data
const copyFile = (source, target, size, callback) => { const sourceFile = path.resolve(__dirname, source); const targetFile = path.resolve(__dirname, target); const buf = Buffer.alloc(size); let hasRead = 0; // 下次讀取文件的位置 let hasWrite = 0; // 下次寫入文件的位置 fs.open(sourceFile, "r", (err, sourceFd) => { if (err) callback(err); fs.open(targetFile, "w", (err, targetFd) => { if (err) throw callback(err); function next() { fs.read(sourceFd, buf, 0, size, hasRead, (err, bytesRead) => { if (err) callback(err); hasRead += bytesRead; if (bytesRead) { fs.write(targetFd, buf, 0, size, hasWrite, (err, bytesWrite) => { if (err) callback(err); hasWrite += bytesWrite; next(); }); return; } fs.close(sourceFd, () => { console.log("關(guān)閉源文件"); }); fs.close(targetFd, () => { console.log("關(guān)閉目標文件"); }); }); } next(); }); }); };
Stream uses
const fs = require("fs"); const path = require("path"); const readStream = fs.createReadStream( path.resolve(__dirname, "../doc/Mobx原理及丐版實現(xiàn).md") ); const writeStream = fs.createWriteStream(path.resolve("target.txt")); readStream.pipe(writeStream);
File upload
Small file upload
// 上傳后資源的URL地址 const RESOURCE_URL = `http://localhost:${PORT}`; // 存儲上傳文件的目錄 const UPLOAD_DIR = path.join(__dirname, "../public"); const storage = multer.diskStorage({ destination: async function (req, file, cb) { // 設(shè)置文件的存儲目錄 cb(null, UPLOAD_DIR); }, filename: function (req, file, cb) { // 設(shè)置文件名 cb(null, `${file.originalname}`); }, }); const multerUpload = multer({ storage }); router.post( "/uploadSingle", async (ctx, next) => { try { await next(); ctx.body = { code: 1, msg: "文件上傳成功", url: `${RESOURCE_URL}/${ctx.file.originalname}`, }; } catch (error) { console.log(error); ctx.body = { code: 0, msg: "文件上傳失敗", }; } }, multerUpload.single("file") );
Large file upload
Main steps
- 前端接收大文件,并進行切片處理
- 將每份切片進行上傳處理
- 后端接收到所有的切片,存儲所有切片到一個文件夾中
- 將文件夾中的切片做合并,并對切片做刪除
- 再次上傳統(tǒng)一文件時,能夠快速上傳
具體實現(xiàn)
前端切片
const BIG_FILE_SIZE = 25 * 1024 * 1024; const SLICE_FILE_SIZE = 5 * 1024 * 1024; const uploadFile = async () => { if (!fileList?.length) return alert("請選擇文件"); const file = fileList[0]; const shouldUpload = await verifyUpload(file.name); if (!shouldUpload) return message.success("文件已存在,上傳成功"); if (file.size > BIG_FILE_SIZE) { // big handle getSliceList(file); } // // normal handle // upload("/uploadSingle", file); }; const getSliceList = (file: RcFile) => { const sliceList: ISlice[] = []; let curSize = 0; let index = 0; while (curSize < file.size) { sliceList.push({ id: shortid.generate(), slice: new File( [file.slice(curSize, (curSize += SLICE_FILE_SIZE))], `${file.name}-${index}` ), name: file.name, sliceName: `${file.name}-${index}`, progress: 0, }); index++; } uploadSlice(sliceList); setSliceList(sliceList); };
file 是一種特殊的 Blob 對象,可以使用 slice 進行大文件分割
上傳切片
const uploadSlice = async (sliceList: ISlice[]) => { const requestList = sliceList .map(({ slice, sliceName, name }: ISlice, index: number) => { const formData = new FormData(); formData.append("slice", slice); formData.append("sliceName", sliceName); formData.append("name", name); return { formData, index, sliceName }; }) .map(({ formData }: { formData: FormData }, index: number) => request.post("/uploadBig", formData, { onUploadProgress: (progressEvent: AxiosProgressEvent) => sliceUploadProgress(progressEvent, index), }) ); await Promise.all(requestList); };
根據(jù)切片構(gòu)建每個切片的 formData,將二進制數(shù)據(jù)放在 slice 參數(shù)中,分別發(fā)送請求。
onUploadProgress 來處理每個切片的上傳進度
// Client const storage = multer.diskStorage({ destination: async function (req, file, cb) { const name = file?.originalname.split(".")?.[0]; const SLICE_DIR = path.join(UPLOAD_DIR, `${name}-slice`); if (!fs.existsSync(SLICE_DIR)) { await fs.mkdirSync(SLICE_DIR); } // 設(shè)置文件的存儲目錄 cb(null, SLICE_DIR); }, filename: async function (req, file, cb) { // 設(shè)置文件名 cb(null, `${file?.originalname}`); }, }); // Server router.post( "/uploadBig", async (ctx, next) => { try { await next(); const slice = ctx.files.slice[0]; // 切片文件 ctx.body = { code: 1, msg: "文件上傳成功", url: `${RESOURCE_URL}/${slice.originalname}`, }; } catch (error) { ctx.body = { code: 0, msg: "文件上傳失敗", }; } }, multerUpload.fields([{ name: "slice" }]) );
切片合并
當我們所有的切片上傳成功之后,我們依舊希望是按著原始文件作為保存的,所以需要對切片進行合并操作
// Client const uploadSlice = async (sliceList: ISlice[]) => { // ...和上述 uploadSlice 一致 mergeSlice(); }; const mergeSlice = () => { request.post("/mergeSlice", { size: SLICE_FILE_SIZE, name: fileList[0].name, }); }; // Server router.post("/mergeSlice", async (ctx, next) => { try { await next(); const { size, name } = ctx.request.body ?? {}; const sliceName = name.split(".")?.[0]; const filePath = path.join(UPLOAD_DIR, name); const slice_dir = path.join(UPLOAD_DIR, `${sliceName}-slice`); await mergeSlice(filePath, slice_dir, size); ctx.body = { code: 1, msg: "文件合并成功", }; } catch (error) { ctx.body = { code: 0, msg: "文件合并失敗", }; } }); // 通過 stream 來讀寫數(shù)據(jù),將 slice 中數(shù)據(jù)讀取到文件中 const pipeStream = (path, writeStream) => { return new Promise((resolve) => { const readStream = fs.createReadStream(path); readStream.on("end", () => { fs.unlinkSync(path); // 讀取完成之后,刪除切片文件 resolve(); }); readStream.pipe(writeStream); }); }; const mergeSlice = async (filePath, sliceDir, size) => { if (!fs.existsSync(sliceDir)) { throw new Error("當前文件不存在"); } const slices = await fs.readdirSync(sliceDir); slices.sort((a, b) => a.split("-")[1] - b.split("-")[1]); try { const slicesPipe = slices.map((sliceName, index) => { return pipeStream( path.resolve(sliceDir, sliceName), fs.createWriteStream(filePath, { start: index * size }) ); }); await Promise.all(slicesPipe); await fs.rmdirSync(sliceDir); // 讀取完成之后,刪除切片文件夾 } catch (error) { console.log(error); } };
上傳文件校驗
當我們上傳一個文件的時候,先去判斷在服務(wù)器上是否存在該文件,如果存在則直接不做上傳操作,否則按上述邏輯進行上傳
// Client const verifyUpload = async (name: string) => { const res = await request.post("/verify", { name }); return res?.data?.data; }; const uploadFile = async () => { if (!fileList?.length) return alert("請選擇文件"); const file = fileList[0]; const shouldUpload = await verifyUpload(file.name); if (!shouldUpload) return message.success("文件已存在,上傳成功"); if (file.size > BIG_FILE_SIZE) { // big handle getSliceList(file); } // // normal handle // upload("/uploadSingle", file); }; // Server router.post("/verify", async (ctx, next) => { try { await next(); const { name } = ctx.request.body ?? {}; const filePath = path.resolve(UPLOAD_DIR, name); if (fs.existsSync(filePath)) { ctx.body = { code: 1, data: false, }; } else { ctx.body = { code: 1, data: true, }; } } catch (error) { ctx.body = { code: 0, msg: "檢測失敗", }; } });
上述直接使用文件名來做判斷,過于絕對,對文件做了相關(guān)修改并不更改名字,就會出現(xiàn)問題。更應(yīng)該采用的方案是根據(jù)文件相關(guān)的元數(shù)據(jù)計算出它的 hash 值來做判斷。
const calculateMD5 = (file: any) => new Promise((resolve, reject) => { const chunkSize = SLICE_FILE_SIZE const fileReader = new FileReader(); const spark = new SparkMD5.ArrayBuffer(); let cursor = 0; fileReader.onerror = () => { reject(new Error('Error reading file')); }; fileReader.onload = (e: any) => { spark.append(e.target.result); cursor += e.target.result.byteLength; if (cursor < file.size) loadNext(); else resolve(spark.end()); }; const loadNext = () => { const fileSlice = file.slice(cursor, cursor + chunkSize); fileReader.readAsArrayBuffer(fileSlice); } loadNext(); });
本文所有的代碼可以github上查看
總結(jié)
本文從文件常識/常用的文件 API 入手,重點講解了 Node 中 File 的相關(guān)實踐,最后使用相關(guān)內(nèi)容實現(xiàn)了大文件上傳。
更多node相關(guān)知識,請訪問:nodejs 教程!
The above is the detailed content of Let's talk in depth about the File module in Node. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

As a C# developer, our development work usually includes front-end and back-end development. As technology develops and the complexity of projects increases, the collaborative development of front-end and back-end has become more and more important and complex. This article will share some front-end and back-end collaborative development techniques to help C# developers complete development work more efficiently. After determining the interface specifications, collaborative development of the front-end and back-end is inseparable from the interaction of API interfaces. To ensure the smooth progress of front-end and back-end collaborative development, the most important thing is to define good interface specifications. Interface specification involves the name of the interface

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

Methods for implementing instant messaging include WebSocket, Long Polling, Server-Sent Events, WebRTC, etc. Detailed introduction: 1. WebSocket, which can establish a persistent connection between the client and the server to achieve real-time two-way communication. The front end can use the WebSocket API to create a WebSocket connection and achieve instant messaging by sending and receiving messages; 2. Long Polling, a technology that simulates real-time communication, etc.

Django: A magical framework that can handle both front-end and back-end development! Django is an efficient and scalable web application framework. It is able to support multiple web development models, including MVC and MTV, and can easily develop high-quality web applications. Django not only supports back-end development, but can also quickly build front-end interfaces and achieve flexible view display through template language. Django combines front-end development and back-end development into a seamless integration, so developers don’t have to specialize in learning

Combination of Golang and front-end technology: To explore how Golang plays a role in the front-end field, specific code examples are needed. With the rapid development of the Internet and mobile applications, front-end technology has become increasingly important. In this field, Golang, as a powerful back-end programming language, can also play an important role. This article will explore how Golang is combined with front-end technology and demonstrate its potential in the front-end field through specific code examples. The role of Golang in the front-end field is as an efficient, concise and easy-to-learn
