节点模块在使用前未初始化

时间:2015-10-04 09:08:06

标签: javascript node.js asynchronous module require

我正在尝试创建我的第一个节点模块以发布到NPM并遇到了一个我无法找到答案的问题。

我决定使用Promises编写模块并保持所有异步。在初始化期间,模块会调用一些花费一些时间访问文件系统的函数。

我的问题是,在通过使用required代码来调用模块之前,模块没有完全初始化。

完整模块在GitHub上,但这里是初始化代码:

var uuid = require('node-uuid')
var fsBlobStoreFactory = require('fs-blob-store')
var Promise = require('bluebird')
var validator = require('validator')
var mkdirp = require('mkdirp')
var path = require('path')
var fs = require('fs')

module.exports = BlobStore

function BlobStore(opts) {
  if (!(this instanceof BlobStore)) {
    return new BlobStore(opts)
  }
  this._parseOpts(opts) // <-- Synchronous
  this.currentBlobPath = ''
  this.fsBlobStore = fsBlobStoreFactory(this.opts.blobStoreRoot) // <-- Synchronous
  this._buildBlobPath().then(() => {
    console.log('Blob Store Initialized');
    console.log('Current Blob Path: ' + this.currentBlobPath);
  }) // <-- This takes a while and is asynchronous
}

这是我用于手动测试的快速js文件:

var crispyStream = require('crispy-stream');
var opts = {
  blobStoreRoot: '/some/dir/blobs',
  dirDepth: 3,
  dirWidth: 3
}
var sbs = require('./index')(opts)
// Any code under here that uses sbs will fail because the module has not finished loading.

var input = 'pipe this';
var pipable = crispyStream.createReadStream(input);
sbs.write().then((ws) => {
  pipable.pipe(ws);
}

据我所知,节点内的模块加载器是同步的,但由于内部函数调用是异步的,require在模块完成初始化之前返回。

我能找到的唯一解决方案是让模块的消费者使用&#39;然后&#39; Promise的方法,或使用回调。

任何指向正确方向的人都会非常感激。

0 个答案:

没有答案