如何在JavaScript Azure函数中共享代码?

如何在Azure函数应用程序中的文件之间共享代码(例如,Mongo模式定义)?

我需要这样做,因为我的function需要访问共享的mongo模式和模型,比如这个基本的例子:

var blogPostSchema = new mongoose.Schema({ id: 'number', title: 'string', date: 'date', content: 'string' }); var BlogPost = mongoose.model('BlogPost', blogPostSchema); 

我已经尝试添加一个"watchDirectories": [ "Shared" ]行到我的host.json并在该文件夹中添加了一个包含上述variables定义的index.js ,但这似乎并没有提供给其他函数。

我只是Exception while executing function: Functions.GetBlogPosts. mscorlib: ReferenceError: BlogPost is not defined得到一个Exception while executing function: Functions.GetBlogPosts. mscorlib: ReferenceError: BlogPost is not defined Exception while executing function: Functions.GetBlogPosts. mscorlib: ReferenceError: BlogPost is not defined

我也试过require .js文件,但是这似乎没有被发现。 这可能是我刚刚弄错了path。

有没有人有一个例子或提示如何共享.js代码之间的azure色的function?

我通过执行以下步骤来解决此问题:

  1. 将一行添加到根hosts.jsonwatch共享文件夹。 "watchDirectories": [ "Shared" ]
  2. 在共享文件夹中,添加了包含以下模式/模型定义和导出的blogPostModel.js文件

共享\ blogPostModel.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); 
  1. 在我的函数require与以下path的共享文件: var blogPostModel = require('../Shared/blogPostModel.js');

然后,我可以build立一个连接,并与模型进行交互,在每个单独的函数中find等等。

该解决scheme由以下SOpost组成:

Node.js中的Azure函数和共享文件

编译Mongoose后无法覆盖模型