diff --git a/uniCloud/cloudfunctions/common/uni-im-ext/index.js b/uniCloud/cloudfunctions/common/uni-im-ext/index.js index 5015171f54fc5ab9b78b94c7437349b32c9f54b6..aa4fd3973a57c814543f67641ed982fe794b953d 100644 --- a/uniCloud/cloudfunctions/common/uni-im-ext/index.js +++ b/uniCloud/cloudfunctions/common/uni-im-ext/index.js @@ -67,6 +67,7 @@ const fs = require('fs'); const path = require('path'); const REGISTER_EXT_CACHE = './_registered_ext.js' +let isFsWritable = false function getSubdirs(parent) { try { @@ -166,18 +167,26 @@ function loadExtensions() { requires.push(`const e_${extSeq} = require('${modDir.replace(/\\/g, '/')}');`) extSeq ++ } - moduleExports = Object.keys(moduleExports).map(exp => { - return `"${exp}": [${moduleExports[exp].join(', ')}]` - }).join(',\n') - // 输出缓存文件 - let registeredExtCache = ` + // 把扫描到的扩展模块写入缓存文件 + if (isFsWritable) { + moduleExports = Object.keys(moduleExports).map(exp => { + return `"${exp}": [${moduleExports[exp].join(', ')}]` + }).join(',\n') + + try { + // 输出缓存文件 + let registeredExtCache = ` ${requires.join('\n')} module.exports = { ${moduleExports} } ` - fs.writeFileSync(path.join(__dirname, REGISTER_EXT_CACHE), registeredExtCache) + fs.writeFileSync(path.join(__dirname, REGISTER_EXT_CACHE), registeredExtCache) + } catch (e) { + // 无法写缓存文件? + } + } return registeredExtensionPoints } @@ -191,12 +200,19 @@ let _registeredExtensionPointsPromise * @returns {any[]} 该扩展点上挂接的所有扩展程序各自的返回值拼装在一个数组里。 */ async function invokeExts(extensionPointName, ...args) { + isFsWritable = (this.getCloudInfo().provider === 'aliyun') + // 尝试从生成的缓存文件中加载 - let registeredExtensionPoints = {} - try { - registeredExtensionPoints = require(REGISTER_EXT_CACHE) - } catch (e) { - // 尚无缓存 + let registeredExtensionPoints + if (isFsWritable) { + try { + registeredExtensionPoints = require(REGISTER_EXT_CACHE) + } catch (e) { + // 尚未生成缓存文件 + } + } + + if (!registeredExtensionPoints) { // 懒加载,避免在调用接口重入时重复解析扩展模块 if (!_registeredExtensionPointsPromise) { _registeredExtensionPointsPromise = new Promise(resolve => { @@ -207,6 +223,7 @@ async function invokeExts(extensionPointName, ...args) { } // console.log('invokeExts:', Object.keys(registeredExtensionPoints), extensionPointName, args) + // 找到指定的扩展点并调用 if (!registeredExtensionPoints[extensionPointName]) return [] return Promise.all( registeredExtensionPoints[extensionPointName]