nodejs-如何保存从telegram bot收到的文件



如何在nodejs中从流或url保存文件?我有一个电报机器人,可以从用户那里获取文件。我可以获得文件url或流,但我不知道如何在处理之前将其保存在临时目录中。

这是我正在使用的库的链接

我该如何继续?这是代码


#!/usr/bin/env node
const process = require('process');
const fs = require('fs');
const path = require('path');
const TelegramBot = require('node-telegram-bot-api');

const token = process.env.TELEGRAM_BOT_TOKEN || '5xxxxxxxxxxxxx';
// Create a bot that uses 'polling' to fetch new updates
const bot = new TelegramBot(token, {polling: true});  
bot.onText(//echo(.+)/, async (msg, match) => {
// 'msg' is the received Message from Telegram
// 'match' is the result of executing the regexp above on the text content
// of the message
//const chatId = msg.chat.id;
});
bot.on('message', async (msg) => {
...
});

bot.on('document', async (data) => {
console.log(data);
// here I'm getting the file url  
const fileURL = await bot.getFileLink(data.document.file_id);
// the library have a method that give the ability to get the file stream. How I save it to a file?
const stream = await bot.getFileStream(data.document.file_id);
console.log(fileURL, stream);
});
//

您可以这样做:

const { createWriteStream } = require('fs');
stream.pipe(createWriteStream('your_file'));

最新更新