当前位置:网站首页>Node文件操作
Node文件操作
2022-07-28 13:27:00 【Parzivval】
Node的一些文件操作问题
常用的读取文件的模块:fs
压缩一个文件
使用的是node-archiver
链接:https://github.com/archiverjs/node-archiver
/** * 将目标文件夹打包 * @param dirname 所需要打包文件或文件夹所在的目录 * @param filename 所需打包的文件/目录名称,也是打包后的zip名称 */
static async zip(dirname:string,filename:string){
let archive = archiver('zip', {
zlib: {
level: 9 } // 设置压缩级别
});
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`));
}
文件哈希值
使用的是node-crypto
/** * 获取文件哈希值 * @param path * @returns */
function createFileHash256Sync(path:string):any {
//读取一个Buffer
const buffer = fs.readFileSync(path);
const fsHash = crypto.createHash('sha256');
fsHash.update(buffer);
const md5 = fsHash.digest('hex');
return md5;
}
使用Form-Data发送压缩文件
使用node-FormData模块
一定记得 import FormData = require(“form-data”); 不然自带的form-data内容只支持blob或者string
传递readStream
// 填充文件
form.append("file",fs.createReadStream(zipPath),{
contentType:"application/octet-stream"
});
// 如果使用form-data传递json对象,要转换成string进行传递
// 填充参数
form.append("parameters", JSON.stringify({
"filehash":filehash,
"boardType":config.boardType,
"compileType":config.compileType
}),{
contentType:"application/json"
});
封装好之后进行发送时发现node-fetch不支持form-data,request支持的formData格式非常简单不是我们用的那种封装好的from-data,所以这里使用其他方式发送请求。
form-data发送请求
let form = new FormData();
form.append("file", fs.createReadStream(zipPath));
// 向C提交文件数据
form.submit('http://10.33.200.1:8700/api/upload', function(err, res) {
res.resume();
return res.send({
code:200,
message:'成功'
})
});
got发送请求
使用got模块
链接: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!
编码后使用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对象发送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})
边栏推荐
- Discrete logarithm problem (DLP) & Diffie Hellman problem (DHP)
- As a programmer, how to manage time efficiently?
- LeetCode 105.从前序与中序遍历序列构造二叉树 && 106.从中序与后序遍历序列构造二叉树
- Detailed explanation of C language student achievement management system [easy to understand]
- Career planning of Software Test Engineer
- JMeter installation tutorial and login add token
- 走进音视频的世界——FLV视频封装格式
- 【LeetCode】1331. 数组序号转换
- 【翻译】盐业公司来Linkerd公司是为了负载平衡,留下来是为了效率、可靠性和性能。...
- What is a spin lock? A spin lock means that when a thread attempts to acquire a lock, if the lock has been occupied by other threads, it will always cycle to detect whether the lock has been released,
猜你喜欢

Leetcode 105. construct binary tree from preorder and inorder traversal sequence & 106. construct binary tree from inorder and postorder traversal sequence

QQ robot configuration record based on nonebot2
![[ecmascript6] set and map](/img/64/dd6ffc5f0faf881b990e609cf62343.png)
[ecmascript6] set and map

Security assurance is based on software life cycle -psp application

Target detection: speed and accuracy comparison (fater r-cnn, r-fcn, SSD, FPN, retinanet and yolov3)

开源项目丨Taier1.2版本发布,新增工作流、租户绑定简化等多项功能

Jmeter安装教程及登录增加token

LeetCode 0143. 重排链表

Multi level cache scheme

在centos中安装mysql5.7.36
随机推荐
【Utils】JsonUtil
用友BIP CRM新品发布,赋能大中型企业营销增长
论文研读--Masked Generative Distillation
2022高处安装、维护、拆除考试题库及在线模拟考试
Security assurance is based on software life cycle -psp application
【Try to Hack】HFish蜜罐部署
指针和数组(7)
How does vos3000 send incoming calls to okcc
深度学习基础----GNN谱域和空域 (不断完善更新积累)
Several solutions to spanning
[try to hack] hfish honeypot deployment
RSA encrypts data with private key and decrypts data with public key (not a signature verification process)
如何有效进行回顾会议(上)?
QQ robot configuration record based on nonebot2
Duplicate data in leetcode (442) array
MiniTest--小程序自动化测试框架
83.(cesium之家)cesium示例如何运行
MVC model: calendar system
Install mysql5.7.36 in CentOS
LeetCode 0143. 重排链表