gpt4 book ai didi

javascript - Node.js:创建一个 txt 文件而不写入设备

转载 作者:行者123 更新时间:2023-12-05 06:05:34 29 4
gpt4 key购买 nike

我有一个问题。在我的项目中,我得到一个文本并将该文本发送到 .txt 文件中的远程 API。现在程序执行此操作:获取文本,将文本保存在文件系统中的 .txt 文件中,将 .txt 文件上传到远程 API。不幸的是,远程 API 只接受文件,我不能在请求中发送纯文本。

//get the wallPost with the field text
fs.writeFileSync(`./tmp/${wallPostId}.txt`, wallPost.text)

remoteAPI.uploadFileFromStorage(
`${wallPostPath}/${wallPostId}.txt`,
`./tmp/${wallPostId}.txt`
)

UPD:在函数 uploadFileFromStorage 中,我通过写入文件向远程 api 发出了 PUT 请求。 Remote API是云存储的API,只能保存文件。

const uploadFileFromStorage = (path, filePath) =>{
let pathEncoded = encodeURIComponent(path)
const requestUrl = `https://cloud-api.yandex.net/v1/disk/resources/upload?&path=%2F${pathEncoded}`
const options = {
headers: headers
}

axios.get(requestUrl, options)

.then((response) => {
const uploadUrl = response.data.href
const headersUpload = {
'Content-Type': 'text/plain',
'Accept': 'application/json',
'Authorization': `${auth_type} ${access_token}`
}
const uploadOptions = {
headers: headersUpload
}
axios.put(
uploadUrl,
fs.createReadStream(filePath),
uploadOptions
).then(response =>
console.log('uploadingFile: data '+response.status+" "+response.statusText)
).catch((error) =>
console.log('error uploadFileFromStorage '+ +error.status+" "+error.statusText)
)
})

但我猜将来这样的过程会很慢。我想在 RAM 内存中创建并上传一个 .txt 文件(不写入驱动器)。感谢您的宝贵时间。

最佳答案

您正在使用 Yandex Disk API,它需要文件,因为这就是它的用途:它明确地将文件存储在远程磁盘上。

因此,如果您查看该代码,提供文件内容的部分是通过 fs.createReadStream(filePath) 提供的,它是一个 Stream。该函数不关心什么构建那个流,它只关心它一个流,所以build your own from your in-memory data :

const { Readable } = require("stream");

...

const streamContent = [wallPost.text];
const pretendFileStream = Readable.from(streamContent);

...

axios.put(
uploadUrl,
pretendFileStream,
uploadOptions
).then(response =>
console.log('uploadingFile: data '+response.status+" "+response.statusText)
)

虽然我在您的代码中没有看到任何内容告诉 Yandex Disk API 文件名应该是什么,但我确信那只是因为您为简洁起见编辑了帖子。

关于javascript - Node.js:创建一个 txt 文件而不写入设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65972284/

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