首页 > 解决方案 > 实例化对象如何导出和导入 JS 文件?

问题描述

我正在编写一个快速 JS 应用程序。我也是 javascript 的新手。我用过 c# 但没有多少 javascript。

我有一个名为:gcs-config.js 的文件,这是该文件的内容:

const path = require("path");
const { Storage } = require("@google-cloud/storage");

const serviceKey = path.join(__dirname, "./config/gcs-keys.json");
const projectId = process.env.GGL_PROJECT_ID;
const bucketName = process.env.GGL_BUCKET_NAME;

const storage = new Storage({
  keyFilename: serviceKey,
  projectId: projectId,
});

exports.storage = storage;
exports.bucketName = bucketName;

如您所见,我正在导出存储类和一个常量;

我在这个名为gcs-helper.js的文件中使用它, 但它抛出一个错误,说 null,我不知道出了什么问题

const storage = require("../config/gcs-config");

async function uploadFile(targetFolder, filePath, fileName, folderType) {
  await storage.bucket(bucketName).upload(filePath, {
    // Support for HTTP requests made with `Accept-Encoding: gzip`
    gzip: true,
    destination: `${folderType}/${targetFolder}/${fileName}`,
    metadata: {
      // Enable long-lived HTTP caching headers
      // Use only if the contents of the file will never change
      // (If the contents will change, use cacheControl: 'no-cache')
      cacheControl: "public, max-age=31536000",
    },
  });

exports.uploadFile = uploadFile;

但是如果我在gcs-helper.js中实例化 Storage 类而不是使用单独的文件,那么它就可以工作。可以随时告诉我出了什么问题吗?

编辑:我尝试控制台记录存储,但得到了不同的结果

这是存储来自另一个文件的第一个:

STORAGE: {
  storage: Storage {
    baseUrl: 'https://storage.googleapis.com/storage/v1',
    apiEndpoint: 'https://storage.googleapis.com',
    timeout: undefined,
    globalInterceptors: [],
    interceptors: [],
    packageJson: {
      name: '@google-cloud/storage',
      description: 'Cloud Storage Client Library for Node.js',
      version: '5.3.0',
      license: 'Apache-2.0',
      author: 'Google Inc.',
      engines: [Object],
      repository: 'googleapis/nodejs-storage',
      main: './build/src/index.js',
      types: './build/src/index.d.ts',
      files: [Array],
      keywords: [Array],
      scripts: [Object],
      dependencies: [Object],
      devDependencies: [Object]
    },
    projectId: 'projectares-291618',
    projectIdRequired: false,
    providedUserAgent: undefined,
    makeAuthenticatedRequest: [Function: makeAuthenticatedRequest] {
      getCredentials: [Function: bound getCredentials],
      authClient: [GoogleAuth]
    },
    authClient: GoogleAuth {
      checkIsGCE: undefined,
      jsonContent: null,
      cachedCredential: null,
      _cachedProjectId: 'projectares-291618',
      keyFilename: 'C:\\Users\\apung\\Desktop\\ProjectAres\\ares-back\\config\\config\\gcs-keys.json',
      scopes: [Array],
      clientOptions: undefined
    },
    getCredentials: [Function: bound getCredentials],
    acl: {
      OWNER_ROLE: 'OWNER',
      READER_ROLE: 'READER',
      WRITER_ROLE: 'WRITER'
    },
    getBucketsStream: [Function],
    getHmacKeysStream: [Function]
  },
  bucketName: 'project-ares-bucket'
}

这是第二个,其中存储在同一个文件上实例化

STORAGE: Storage {
  baseUrl: 'https://storage.googleapis.com/storage/v1',
  apiEndpoint: 'https://storage.googleapis.com',
  timeout: undefined,
  globalInterceptors: [],
  interceptors: [],
  packageJson: {
    name: '@google-cloud/storage',
    description: 'Cloud Storage Client Library for Node.js',
    version: '5.3.0',
    license: 'Apache-2.0',
    author: 'Google Inc.',
    engines: { node: '>=10' },
    repository: 'googleapis/nodejs-storage',
    main: './build/src/index.js',
    types: './build/src/index.d.ts',
    files: [ 'build/src', '!build/src/**/*.map' ],
    keywords: [
      'google apis client',
      'google api client',
      'google apis',
      'google api',
      'google',
      'google cloud platform',
      'google cloud',
      'cloud',
      'google storage',
      'storage'
    ],
    scripts: {
      predocs: 'npm run compile',
      docs: 'jsdoc -c .jsdoc.js',
      'system-test': 'mocha build/system-test --timeout 600000 --exit',
      'conformance-test': 'mocha build/conformance-test',
      'preconformance-test': 'npm run compile',
      'presystem-test': 'npm run compile',
      test: 'c8 mocha build/test',
      pretest: 'npm run compile',
      lint: 'gts check',
      'samples-test': 'npm link && cd samples/ && npm link ../ && npm test && cd ../',
      'all-test': 'npm test && npm run system-test && npm run samples-test',
      check: 'gts check',
      clean: 'gts clean',
      compile: 'tsc -p .',
      fix: 'gts fix',
      prepare: 'npm run compile',
      'docs-test': 'linkinator docs',
      'predocs-test': 'npm run docs',
      benchwrapper: 'node bin/benchwrapper.js',
      prelint: 'cd samples; npm link ../; npm install',
      precompile: 'gts clean',
      'api-extractor': 'api-extractor run --local',
      'api-documenter': 'api-documenter yaml --input-folder=temp'
    },
    dependencies: {
      '@google-cloud/common': '^3.3.0',
      '@google-cloud/paginator': '^3.0.0',
      '@google-cloud/promisify': '^2.0.0',
      arrify: '^2.0.0',
      compressible: '^2.0.12',
      'concat-stream': '^2.0.0',
      'date-and-time': '^0.14.0',
      duplexify: '^3.5.0',
      extend: '^3.0.2',
      gaxios: '^3.0.0',
      'gcs-resumable-upload': '^3.1.0',
      'hash-stream-validation': '^0.2.2',
      mime: '^2.2.0',
      'mime-types': '^2.0.8',
      onetime: '^5.1.0',
      'p-limit': '^3.0.1',
      pumpify: '^2.0.0',
      snakeize: '^0.1.0',
      'stream-events': '^1.0.1',
      'xdg-basedir': '^4.0.0'
    },
    devDependencies: {
      '@google-cloud/pubsub': '^2.0.0',
      '@grpc/grpc-js': '^1.0.3',
      '@grpc/proto-loader': '^0.5.1',
      '@types/compressible': '^2.0.0',
      '@types/concat-stream': '^1.6.0',
      '@types/configstore': '^4.0.0',
      '@types/date-and-time': '^0.13.0',
      '@types/extend': '^3.0.0',
      '@types/mime': '^2.0.0',
      '@types/mime-types': '^2.1.0',
      '@types/mocha': '^8.0.0',
      '@types/nock': '^10.0.0',
      '@types/node': '^11.13.4',
      '@types/node-fetch': '^2.1.3',
      '@types/proxyquire': '^1.3.28',
      '@types/pumpify': '^1.4.1',
      '@types/sinon': '^9.0.0',
      '@types/tmp': '0.2.0',
      '@types/uuid': '^8.0.0',
      '@types/xdg-basedir': '^2.0.0',
      c8: '^7.0.0',
      codecov: '^3.0.0',
      'form-data': '^3.0.0',
      gts: '^2.0.0',
      jsdoc: '^3.6.2',
      'jsdoc-fresh': '^1.0.1',
      'jsdoc-region-tag': '^1.0.2',
      linkinator: '^2.0.0',
      mocha: '^8.0.0',
      nock: '~13.0.0',
      'node-fetch': '^2.2.0',
      'normalize-newline': '^3.0.0',
      proxyquire: '^2.1.3',
      sinon: '^9.0.0',
      tmp: '^0.2.0',
      typescript: '^3.8.3',
      uuid: '^8.0.0',
      yargs: '^15.0.0',
      '@microsoft/api-documenter': '^7.8.10',
      '@microsoft/api-extractor': '^7.8.10'
    }
  },
  projectId: 'projectares-291618',
  projectIdRequired: false,
  providedUserAgent: undefined,
  makeAuthenticatedRequest: [Function: makeAuthenticatedRequest] {
    getCredentials: [Function: bound getCredentials],
    authClient: GoogleAuth {
      checkIsGCE: undefined,
      jsonContent: null,
      cachedCredential: null,
      _cachedProjectId: 'projectares-291618',
      keyFilename: 'C:\\Users\\apung\\Desktop\\ProjectAres\\ares-back\\config\\gcs-keys.json',
      scopes: [Array],
      clientOptions: undefined
    }
  },
  authClient: GoogleAuth {
    checkIsGCE: undefined,
    jsonContent: null,
    cachedCredential: null,
    _cachedProjectId: 'projectares-291618',
    keyFilename: 'C:\\Users\\apung\\Desktop\\ProjectAres\\ares-back\\config\\gcs-keys.json',
    scopes: [
      'https://www.googleapis.com/auth/iam',
      'https://www.googleapis.com/auth/cloud-platform',
      'https://www.googleapis.com/auth/devstorage.full_control'
    ],
    clientOptions: undefined
  },
  getCredentials: [Function: bound getCredentials],
  acl: { OWNER_ROLE: 'OWNER', READER_ROLE: 'READER', WRITER_ROLE: 'WRITER' },
  getBucketsStream: [Function],
  getHmacKeysStream: [Function]
}

标签: javascriptexpressnodes

解决方案


您可以按照下面给出的方式导入模块,并通过此站点https://www.sitepoint.com/understanding-module-exports-exports-node-js/更好地了解模块导出和导入。

const gcsConfig = require("../config/gcs-config");

async function uploadFile(targetFolder, filePath, fileName, folderType) {
  await gcsConfig.storage.bucket(bucketName).upload(filePath, {
    // Support for HTTP requests made with `Accept-Encoding: gzip`
    gzip: true,
    destination: `${folderType}/${targetFolder}/${fileName}`,
    metadata: {
      // Enable long-lived HTTP caching headers
      // Use only if the contents of the file will never change
      // (If the contents will change, use cacheControl: 'no-cache')
      cacheControl: "public, max-age=31536000",
    },
  });

exports.uploadFile = uploadFile;


推荐阅读