首页 > 解决方案 > GCP 云功能:找不到 npm 模块

问题描述

所以我正在构建一个云功能,并将我的代码结构化为多个文件。

我的 index.js 是这样的:

const { postHandler } = require('./requestHandler.js');

const httpHandler = (req, res) => {
  const { method } = req;

  switch (method) {
    case 'POST':
      postHandler(req, res);
      break;
    case 'GET':
      getHandler(req, res);
      break;
    case 'DELETE':
      deleteHandler(req, res);
      break;
    case 'PUT':
      putHandler(req, res);
      break;
    default:
      return res.sendStatus(400).json({message: 'Invalid method. Allowed are POST, GET, DELETE'});
  }
}

exports.httpHandler = httpHandler

这是 requestHandler

const createReviewApp = require('./createReviewApp')

const postHandler = ( req, res ) => {
  const { path } = req;
  return createReviewApp( req, res )
}

module.exports = { postHandler }

这是 createReviewApp

const _compute = require('./computeClass.js');
const _dns = require('./dnsClass.js');
const _storage = require('./storageClass.js');

const createReviewApp = ( req, res ) => {
     // doing something
}

这是我的computeClass

const Compute = require('@google-cloud/compute')

const projectId = process.env.GOOGLE_PROJECT_ID;

class ComputeSingleton {
  constructor(){
    this.compute = new Compute({
      projectId,
    });
  }
  getVm({zoneName, vmName}){
    return this.getZone({zoneName}).vm(vmName).get();
  }
  getZone({zoneName}){
    return this.compute.zone(zoneName);
  }
  createVm({zoneName, vmName, config}){
    return this.getZone({zoneName}).createVM(vmName, config);
  }
  deleteVm({zoneName, vmName}){
    return this.getZone({zoneName}).vm(vmName).delete();
  }
}

module.exports = new ComputeSingleton()

现在,在我的 computeClass 中,我收到以下错误:

 Cannot find module '@google-cloud/compute

我已经安装了依赖项,是否需要将所有代码放在一个文件中?

编辑:我在功能 nodejs 模拟器上测试它

标签: node.jsgoogle-cloud-platformgoogle-cloud-functions

解决方案


不,您不需要将代码放在一个文件中。听起来你实际上并没有@google-cloud/compute在你的函数项目 package.json 中完全安装。


推荐阅读