gpt4 book ai didi

node.js - 如何从 Node.js 中的 createReadStream 读取文件?

转载 作者:行者123 更新时间:2023-12-04 15:22:13 26 4
gpt4 key购买 nike

我有可以上传 excel 文件的网络应用程序。如果用户上传,应用程序应该解析它并返回文件中的一些行。所以,应用程序不需要将文件保存到它的文件系统。解析文件并返回行是一项工作。但是下面的代码,我今天早上写的,它将文件保存到它的服务器然后解析它。我认为这是浪费服务器资源。

我不知道如何使用 createReadStream 读取 excel 文件。不保存文件,如何直接解析excel?我对fs不熟悉,当然可以在作业完成后删除文件,但是有什么优雅的方法吗?

import { createWriteStream } from 'fs'
import path from 'path'
import xlsx from 'node-xlsx'

// some graphql code here...


async singleUpload(_, { file }, context) {
try {
console.log(file)
const { createReadStream, filename, mimetype, encoding } = await file

await new Promise((res) =>
createReadStream()
.pipe(createWriteStream(path.join(__dirname, '../uploads', filename)))
.on('close', res)
)

const workSheetsFromFile = xlsx.parse(path.join(__dirname, '../uploads', filename))
for (const row of workSheetsFromFile[0].data) {
console.log(row)
}

return { filename }
} catch (e) {
throw new Error(e)
}
},

最佳答案

使用 express-fileupload 库为上传的文件提供缓冲区表示(通过 data 属性),结合 excel.js 接受缓冲区将带您到达那里。

参见 Express-fileuploadExcel.js

// read from a file
const workbook = new Excel.Workbook();
await workbook.xlsx.readFile(filename);
// ... use workbook


// read from a stream
const workbook = new Excel.Workbook();
await workbook.xlsx.read(stream);
// ... use workbook


// load from buffer // this is what you're looking for
const workbook = new Excel.Workbook();
await workbook.xlsx.load(data);
// ... use workbook

这是一个简化的例子:

const app = require('express')();
const fileUpload = require('express-fileupload');
const { Workbook } = require('exceljs');

app.use(fileUpload());

app.post('/', async (req, res) => {
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send('No files were uploaded.');
}
// The name of the input field (i.e. "myFile") is used to retrieve the uploaded file
await new Workbook().xlsx.load(req.files.myFile.data)
});

app.listen(3000)

关于node.js - 如何从 Node.js 中的 createReadStream 读取文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63066271/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com