当前位置:网站首页>Node file operation
Node file operation
2022-07-28 14:23:00 【Parzivval】
Node Some file operation problems of
Common modules for reading files :fs
Compress a file
It uses node-archiver
link :https://github.com/archiverjs/node-archiver
/** * Package the destination folder * @param dirname The directory where the package file or folder is located * @param filename Files to be packaged / Directory name , It's also packed zip name */
static async zip(dirname:string,filename:string){
let archive = archiver('zip', {
zlib: {
level: 9 } // Set compression level
});
let output = fs.createWriteStream(dirname+`/${
filename}.zip`);
console.log("file is zipping!");
archive.pipe(output);
archive.directory(dirname+filename+"/",false);
await archive.finalize();
console.log("Util.zip:"+fs.existsSync(dirname+`/${
filename}.zip`));
}
File hash value
It uses node-crypto
/** * Get file hash value * @param path * @returns */
function createFileHash256Sync(path:string):any {
// Read a Buffer
const buffer = fs.readFileSync(path);
const fsHash = crypto.createHash('sha256');
fsHash.update(buffer);
const md5 = fsHash.digest('hex');
return md5;
}
Use Form-Data Send compressed file
Use node-FormData modular
Do remember import FormData = require(“form-data”); Otherwise, it comes with form-data Content only supports blob perhaps string
Pass on readStream
// Fill in the file
form.append("file",fs.createReadStream(zipPath),{
contentType:"application/octet-stream"
});
// If you use form-data Pass on json object , To convert to string To pass
// Filling parameters
form.append("parameters", JSON.stringify({
"filehash":filehash,
"boardType":config.boardType,
"compileType":config.compileType
}),{
contentType:"application/json"
});
When sending after encapsulation node-fetch I won't support it form-data,request Supported by formData The format is very simple, and it is not encapsulated like the one we use from-data, So here we use other ways to send the request .
form-data Send a request
let form = new FormData();
form.append("file", fs.createReadStream(zipPath));
// towards C Submit file data
form.submit('http://10.33.200.1:8700/api/upload', function(err, res) {
res.resume();
return res.send({
code:200,
message:' success '
})
});
got Send a request
Use got modular
link :https://github.com/sindresorhus/got
npm install got
import {
FormData} from "formdata-node"
// I assume Got >= 12.x is used for this example
import got from "got"
const form = new FormData()
form.set("greeting", "Hello, World!")
const data = await got.post("https://httpbin.org/post", {
body: form}).json()
console.log(data.form.greeting) // => Hello, World!
Use after coding fetch
import {
Readable} from "stream"
import {
FormDataEncoder} from "form-data-encoder"
import {
FormData} from "formdata-node"
// Note that `node-fetch` >= 3.x have builtin support for spec-compliant FormData, sou you'll only need the `form-data-encoder` if you use `node-fetch` <= 2.x.
import fetch from "node-fetch"
const form = new FormData()
form.set("field", "Some value")
const encoder = new FormDataEncoder(form)
const options = {
method: "post",
headers: encoder.headers,
body: Readable.from(encoder)
}
await fetch("https://httpbin.org/post", options)
File Object to send fetch
import {
FormData, File} from "formdata-node" // You can use `File` from fetch-blob >= 3.x
import fetch from "node-fetch"
const form = new FormData()
const file = new File(["My hovercraft is full of eels"], "file.txt")
form.set("file", file)
await fetch("https://httpbin.org/post", {
method: "post", body: form})
边栏推荐
猜你喜欢

UI开发中所遇到的各种坑

2022年安全员-A证操作证考试题库模拟考试平台操作

一些企业数据平台建设的思考

C语言中浮点数据类型(你学废了吗)

Forage QR code -- online QR code generator

走进音视频的世界——FLV视频封装格式

QQ robot configuration record based on nonebot2

Multi level cache scheme
![[server data recovery] HP StorageWorks series server RAID5 offline data recovery of two disks](/img/23/4d07adcb5fb2c3b4c5090dacd02c89.jpg)
[server data recovery] HP StorageWorks series server RAID5 offline data recovery of two disks

Open source project - taier1.2 release, new workflow, tenant binding simplification and other functions
随机推荐
分集技术简略
开源项目丨Taier1.2版本发布,新增工作流、租户绑定简化等多项功能
As a programmer, how to manage time efficiently?
C语言中浮点数据类型(你学废了吗)
Leetcode 0143. rearrange linked list
这3款在线PS工具,得试试
[lvgl events] Application of events on different components (I)
Database optimization understanding these is enough
【Try to Hack】HFish蜜罐部署
天气这么热太阳能发电不得起飞喽啊?喽啊个头……
Iterator iterator interface
[translation] how to choose a network gateway for your private cloud
JS instantiation method
Xcode编写SwiftUI代码时一个编译通过但导致预览(Preview)崩溃的小陷阱
一些企业数据平台建设的思考
AFNetworking速成教程
解决uniapp微信小程序canvas不能引入字体的问题
Custom Configuration Sections
7.27模拟赛总结
QML picture preview