这里下载文件用了axios去下载
下载:
public async download_from(url, fileName) { return new Promise(async (resolve, reject) => { const download_dir = path.join( process.cwd(), AppConfig.config.download_file_path, this._job_id ); const local_path = path.join(download_dir, fileName); //下载文件到指定的文件夹路径下,如果没有的话就创建一下 if (!fs.existsSync(download_dir)) { fs.mkdirSync(download_dir, { recursive: true }); } const fileWriter = fs.createWriteStream(local_path); console.log(`文件:${local_path}开始下载,地址是:${url}`); try { const response = await axios.get(url, { responseType: "stream" }); if (response.status === 200) { response.data.pipe(fileWriter); fileWriter.on("finish", () => { console.log(`文件:${local_path}下载完成`); fileWriter.close(); resolve(local_path); }); } else { console.log(`文件:${local_path}下载出错:${response}`); reject(`Error: ${response}`); } } catch (error) { console.log(`文件:${local_path}下载异常:${error}`); reject(`Error: ${error}`); } }); }
删除文件夹:
/** * 这里场景是可能你需要下载后上传到某个目录,然后删除这个下载文件存储的临时文件夹, * @param download_file_path 下载后存储的地址 */ public del_local_file(download_file_path) { try { //本次任务下载的文件夹 const download_dir = path.join( process.cwd(), download_file_path, this._job_id ); //下载上传后删除服务上的临时文件夹 fs.rmdir(download_dir, { recursive: true }, (err) => { if (err) { Logger.INSTANCE.error("Error removing folder:", err); throw err; } else { Logger.INSTANCE.info("Folder removed successfully", download_dir); } }); } catch (error) { Logger.INSTANCE.error("del_local_file_error:", error); throw error; } }
标签:nodejs,URL,文件夹,dir,error,download,path,local,下载 From: https://www.cnblogs.com/llcdbk/p/17993194