How to share code in JavaScript Azure Functions?(如何在 JavaScript Azure Functions 中共享代码?)
问题描述
如何在 Azure 函数应用中的文件之间共享代码(例如 Mongo 架构定义)?
How can I share code (e.g. Mongo schema definitions) between files in an Azure function app?
我需要这样做,因为我的函数需要访问共享的 mongo 架构和模型,例如这个基本示例:
I need to do this, as my functions require access to a shared mongo schema and models, such as this basic example:
var blogPostSchema = new mongoose.Schema({
id: 'number',
title: 'string',
date: 'date',
content: 'string'
});
var BlogPost = mongoose.model('BlogPost', blogPostSchema);
我尝试在 host.json 中添加 "watchDirectories": [ "Shared" ] 行,并在该文件夹中添加了 index.html.js 包含上述变量定义,但这似乎不适用于其他函数.
I've tried to add a "watchDirectories": [ "Shared" ] line to my host.json and in that folder added an index.js containing the above variable definition but this doesn't seem to be available to the other functions.
我只是在执行函数时得到一个异常:Functions.GetBlogPosts.mscorlib:ReferenceError:未定义博客帖子.
I simply get a Exception while executing function: Functions.GetBlogPosts. mscorlib: ReferenceError: BlogPost is not defined.
我也尝试过明确地require .js 文件,但这似乎没有找到.可能是我走错了路.
I've also tried explitely requireing the .js file, but this seems not to be found. It could be I just got the path wrong.
有人有关于如何在 azure 函数之间共享 .js 代码的示例或提示吗?
Does anyone have an example or tips on how to share .js code between azure functions?
推荐答案
我通过以下步骤解决了这个问题:
I fixed this issue by doing the following steps:
- 在根
hosts.json中添加一行以watch共享文件夹.watchDirectories":[共享"] - 在共享文件夹中,添加了一个
blogPostModel.js文件,其中包含以下架构/模型定义和导出
- Add a line to the root
hosts.jsontowatcha shared folder."watchDirectories": [ "Shared" ] - In the shared folder, added a
blogPostModel.jsfile containing the following schema/model definition and export
sharedlogPostModel.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var blogPostSchema = new Schema({
id: 'number',
title: 'string',
date: 'date',
content: 'string'
});
module.exports = mongoose.model('BlogPost', blogPostSchema);
- 在我的函数
require中,共享文件的路径如下:var blogPostModel = require('../Shared/blogPostModel.js');
- In my function
requirethe shared file with the following path:var blogPostModel = require('../Shared/blogPostModel.js');
然后我可以建立连接并与模型交互,在每个单独的函数中执行 find 等操作.
I can then make a connection and interact with the model doing finds etc in each individual function.
此解决方案由以下 SO 帖子组成:
This solution was composed from the following SO posts:
Node.js 中的 Azure 函数和共享文件
Mongoose 编译后无法覆盖模型
这篇关于如何在 JavaScript Azure Functions 中共享代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 JavaScript Azure Functions 中共享代码?
基础教程推荐
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
