我需要我的机器人保存照片到我的电脑,在那里它正在运行,到指定的路径。此函数:
const fs = require('fs');
const path = require('path');
...
bot.on('photo', (msg) => {
const chatId = msg.chat.id;
const photo = msg.photo[0];
const fileId = photo.file_id;
const fileName = `${chatId}.jpg`;
const filePath = `D:/bot/${fileName}`;
bot.downloadFile(fileId, filePath)
.then(() => {
bot.sendMessage(chatId, 'Done!');
})
.catch((downloadErr) => {
console.error('Error downloading photo:', downloadErr);
bot.sendMessage(chatId, 'Error while saving.');
});
});
我得到一个错误
Error downloading photo: [Error: ENOENT: no such file or directory, open 'D:\bot\248408814.jpg\file_12.jpg']
为什么他要留下从电报下载的文件名?我希望照片位于此文件路径中:'D:\bot\248408814.jpg'
1条答案
按热度按时间svgewumm1#
第二个参数应该是保存图像的文件夹,而不是完整的路径。这就是为什么你得到'没有这样的文件或目录',因为它试图找到该文件夹,这是不存在的。
将
filePath
设置为目录路径,例如:您需要确保作为第二个参数传递的文件夹存在;
How to create a directory if it doesn't exist using Node.js
关于OP关于更改文件名的评论,this issue也问了同样的问题,似乎没有这个选项。
查看
downloadFile
的源代码,没有更改名称的选项。但是,
downloadFile
返回一个Promise,它包含filePath
,然后您可以使用fs
重命名文件:Renaming files using node.js