Azure Functions Node.js V4中如何获取函数目录以加载外部文件?
Azure Functions Node.js V4 获取函数目录方案
在Node.js V4版本的Azure Functions中,原V3版本的context.executionContext.functionDirectory属性已被移除,可通过以下方式获取函数目录:
1. CommonJS模块场景
若函数使用CommonJS模块(.js文件,依赖require导入),直接使用__dirname即可,它会返回当前函数文件所在的目录,也就是目标函数目录。
示例代码:
const path = require('path'); // 拼接外部文件路径 const externalFile = path.join(__dirname, './your-external-file.js'); // 加载外部文件 const externalModule = require(externalFile);
2. ES模块场景
若使用ES模块(.mjs文件或package.json中设置"type": "module"),Node.js默认不提供__dirname,可通过import.meta.url手动计算得到:
示例代码:
import path from 'path'; import { fileURLToPath } from 'url'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); // 拼接外部文件路径 const externalFile = path.join(__dirname, './your-external-file.json'); // 加载外部文件(以读取JSON为例) import fs from 'fs/promises'; const fileContent = JSON.parse(await fs.readFile(externalFile, 'utf8'));
内容的提问来源于stack exchange,提问作者droptix
相关产品推荐
相关产品推荐

