How to share code in JavaScript Azure Functions? How to share code in JavaScript Azure Functions? azure azure

How to share code in JavaScript Azure Functions?


I fixed this issue by doing the following steps:

  1. Add a line to the root hosts.json to watch a shared folder. "watchDirectories": [ "Shared" ]
  2. In the shared folder, added a blogPostModel.js file containing the following schema/model definition and export

shared\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. In my function require the shared file with the following path:var blogPostModel = require('../Shared/blogPostModel.js');

I can then make a connection and interact with the model doing finds etc in each individual function.

This solution was composed from the following SO posts:

Azure Function in Node.js and shared files

Cannot overwrite model once compiled Mongoose