【发布时间】:2016-06-01 23:06:45
【问题描述】:
我正在尝试做一些我认为很简单的事情。我正在使用 nwjs(以前称为 Node-Webkit),如果您不知道这基本上意味着我正在使用 Chromium 和 Node 开发桌面应用程序,其中 DOM 与 Node.js 在同一范围内。我想将工作卸载给网络工作者,这样当我将一些文本发送到 Ivona Cloud(使用 ivona-node)时 GUI 不会挂起,这是一个文本到语音 API。音频在生成并写入 MP3 时以块的形式返回。 ivona-node 使用 fs 将 mp3 写入驱动器。我让它在 dom 中工作,但需要 webworkers 才能不挂起 UI。所以我有两个节点模块需要在 webworker 中使用,ivona-node 和 fs。
问题是在 webworker 中你不能使用 require。所以我尝试用browserify打包ivona-node和fs(我使用了一个名为browserify-fs的包)并用importScripts()替换了require。现在我在节点模块中遇到 var 错误。
注意:我认为 native_fs_ 的方法不适用于将 mp3 以块(流)的形式写入磁盘,并且我在 Ivona 包中也遇到了错误(实际上首先)我不知道如何解决。我包含了所有信息以重现此内容。
这是我在控制台中遇到的错误:Uncaught SyntaxError: Unexpected token var VM39 ivonabundle.js:23132
- 在 NWJS 中重现的步骤:
npm install ivona-node
npm install browserify-fs
npm install -g browserify
- 现在我对 ivona-node 的 main.js 和 browserify-fs 的 index.js 进行了浏览:
浏览 main.js > ivonabundle.js
浏览 index.js > fsbundle.js
package.json...
{
"name": "appname",
"description": "appdescr",
"title": "apptitle",
"main": "index.html",
"window":
{
"toolbar": true,
"resizable": false,
"width": 800,
"height": 500
},
"webkit":
{
"plugin": true
}
}
index.html...
<html>
<head>
<title>apptitle</title>
</head>
<body>
<p><output id="result"></output></p>
<button onclick="startWorker()">Start Worker</button>
<button onclick="stopWorker()">Stop Worker</button>
<br><br>
<script>
var w;
function startWorker() {
if(typeof(Worker) !== "undefined") {
if(typeof(w) == "undefined") {
w = new Worker("TTMP3.worker.js");
w.postMessage(['This is some text to speak.']);
}
w.onmessage = function(event) {
document.getElementById("result").innerHTML = event.data;
};
} else {
document.getElementById("result").innerHTML = "Sorry! No Web Worker support.";
}
}
function stopWorker() {
w.terminate();
w = undefined;
}
</script>
</body>
</html>
TTMP3.worker.js...
importScripts('node_modules/browserify-fs/fsbundle.js','node_modules/ivona-node/src/ivonabundle.js');
onmessage = function T2MP3(Text2Speak)
{
postMessage(Text2Speak.data[0]);
//var fs = require('fs'),
// Ivona = require('ivona-node');
var ivona = new Ivona({
accessKey: 'xxxxxxxxxxx',
secretKey: 'xxxxxxxxxxx'
});
//ivona.listVoices()
//.on('end', function(voices) {
//console.log(voices);
//});
// ivona.createVoice(text, config)
// [string] text - the text to be spoken
// [object] config (optional) - override Ivona request via 'body' value
ivona.createVoice(Text2Speak.data[0], {
body: {
voice: {
name: 'Salli',
language: 'en-US',
gender: 'Female'
}
}
}).pipe(fs.createWriteStream('text.mp3'));
postMessage("Done");
}
【问题讨论】:
-
你必须把它保存到磁盘吗?如果您真的需要,您可以将工作人员的 bin 数据发送到顶部以保存,但我不明白为什么它需要保存。
-
也许吧,但是我从 ivona-node 得到的错误呢?我没有让他们进入 dom,只是在 webworker 中。
-
Uncaught SyntaxError: Unexpected token var VM39 ivonabundle.js:23132
-
为什么不使用
require('child_process').fork? -
我不想加载一个新的 nwjs 实例来做这件事。这将是非常昂贵的资源。
标签: javascript node.js requirejs node-webkit web-worker