如何避免库中的默认错误

How to avoid default errors from a library

我创建了一个实际有效的代码,但我调用了一个有错误的库,我想知道是否可以避免该特定代码行。我会尽量解释清楚的:

错误

Uncaught TypeError: fs.openSync is not a function

前码

function synthesizeToAudioFile(authorizationToken, message) {

    // replace with your own subscription key,
    // service region (e.g., "westus"), and
    // the name of the file you save the synthesized audio.
    var serviceRegion = "westus"; // e.g., "westus"
    var filename = "./audiocue.wav";

    //Use token.Otherwise use the provided subscription key
    var audioConfig, speechConfig;
    audioConfig = SpeechSDK.AudioConfig.fromAudioFileOutput(filename);
    speechConfig = SpeechSDK.SpeechConfig.fromAuthorizationToken(authorizationToken, serviceRegion);

    // create the speech synthesizer.
    var synthesizer = new SpeechSDK.SpeechSynthesizer(speechConfig, audioConfig);

    // start the synthesizer and wait for a result.
    synthesizer.speakTextAsync(message,
        function (result) {
            if (result.reason === SpeechSDK.ResultReason.SynthesizingAudioCompleted) {
                console.log("synthesis finished.");
            } else {
                console.error("Speech synthesis canceled, " + result.errorDetails +
                    "\nDid you update the subscription info?");
            }
            synthesizer.close();
            synthesizer = undefined;
        },
        function (err) {
            console.trace("err - " + err);
            synthesizer.close();
            synthesizer = undefined;
        });
    console.log("Now synthesizing to: " + filename);

}

我创建了一个方法,后来我在当前代码中复制了该方法。区别在于我使用 BrowserifyHTML 文件的 script 导入库:

    <script type="text/javascript" src="js/dist/sub_mqtt.js"></script>

这个文件有我的方法,还有整个库,这让它变得疯狂不可读,因此我开始使用 ScriptJS 导入它。问题是,使用 browserify 我能够删除使用 fs.openSync 失败的代码行(我什至不需要),但是通过使用 ScriptJS 导入它我无权访问源代码。

我假设缺少的是我没有导入库 fs,在导入之前我用 ScriptJS 导入的库正在使用它,但是怎么可能我做吗?我试过:

    <script src="../text-to-speech/node_modules/fs.realpath/index.js"></script>

,或

    <script type="text/javascript" src="../text-to-speech/node_modules/fs.realpath/index.js"></script>

并用

包装 synthesizeToAudioFile() 的内容
    require(["node_modules/fs.realpath/index.js"], function (fs) { });

但我收到以下错误:

Uncaught ReferenceError: module is not defined at index.js:1

在研究了这个问题后,我发现了下一个说法:

The fs package on npm was empty and didn't do anything, however many packages mistakenly depended on it. npm, Inc. has taken ownership of it.

It's also a built-in Node module. If you've depended on fs, you can safely remove it from your package dependencies.

因此我所做的是访问我需要的文件 ScriptJS

 require(["../text-to-speech/microsoft.cognitiveservices.speech.sdk.bundle.js"]

直接把上面的那一行去掉。请注意,至少在我的情况下,需要清除浏览器的缓存。