/* 基础小工具,可通用于服务端和用户端 */ const fs = require('fs') const path = require('path') module.exports = { sleep: (ms) => new Promise((resolve, reject) => setTimeout(resolve, ms)), parseJsonPossible(value) { try { return JSON.parse(value) } catch (e) { return value } }, sortAndFilterJson({ fields, entity, exclude = [] } = {}) { const newEntity = {} for (let key of Object.keys(fields).sort()) { if (typeof (entity[key] !== 'undefined') && !Number.isNaN(entity[key]) && entity[key] !== Infinity) { newEntity[key] = entity[key] } } for (let exkey of exclude) { delete newEntity[exkey] } return JSON.stringify(newEntity) }, getDynamicConfig(dynamicConfigFile='ConfigDynamic.js') { // dynamicConfigFile should be absolute or relative to the node process's dir. const fullpath = path.join(process.cwd(), dynamicConfigFile) if (fs.existsSync(fullpath)) { delete require.cache[require.resolve(fullpath)] // delete require.cache[fullpath] 不起作用 return require(fullpath) } else { return {} } }, }