我正在使用 QtScript 来自动化我的应用程序的某些部分以用于开发和测试目的。我已经到了要测试断言的地步,并且基于 "standalone assertion libraries?"以及我在 Debian 存储库中可以找到的东西,我选择了 Should.js。
我无法将它加载到我的 Qt 应用程序中,因为它依赖于 Node 的 require()
功能。我尝试实现这个版本,从 "Supporting require() of CommonJS" 开始并以下面的代码结尾。
它能否奏效,还是我注定要采用这种方法?将 should.js 的位复制到单个文件中可能会更好吗?我不想让自己负责保持 fork 是最新的。 (许可不是问题,因为我不打算重新分发此代码)。
这是我的 MCVE;抱歉,我不能再短了!
应该.cpp
#include <QCoreApplication>
#include <QDateTime>
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QScriptEngine>
#include <QScriptContext>
#include <QScriptContextInfo>
#include <QTextStream>
// Primitive implementation of Node.js require().
// N.B. Supports only .js sources.
QScriptValue require(QScriptContext* context, QScriptEngine* engine)
{
const QString moduleName = context->argument(0).toString();
// First, look in our modules cache
QScriptValue modules = engine->globalObject().property("$MODULES");
QScriptValue module = modules.property(moduleName);
if (module.isValid()) {
auto cached_file = module.property("filename");
auto time_stamp = module.property("timestamp");
auto code = module.property("code");
if (code.isObject() && cached_file.isString() && time_stamp.isDate()) {
if (QFileInfo(cached_file.toString()).lastModified() == time_stamp.toDateTime()) {
qDebug() << "found up-to-date module for require of" << moduleName;
return code;
} else {
qDebug() << "cache stale for" << moduleName;
}
}
} else {
// Prepare a cache entry, as some modules recursively include each
// other. This way, they at least get the partial definition of the
// other, rather than a stack overflow.
module = engine->newObject();
modules.setProperty(moduleName, module);
}
qDebug() << "require" << moduleName;
// resolve filename relative to the calling script
QString filename = moduleName + ".js";
for (auto *p = context; p; p = p->parentContext()) {
QScriptContextInfo info(p);
auto parent_file = info.fileName();
if (parent_file.isEmpty())
continue;
// else, we reached a context with a filename
QDir base_dir = QFileInfo(parent_file).dir();
filename = base_dir.filePath(filename);
if (QFile::exists(filename)) {
break;
}
}
QFile file(filename);
if (!file.open(QIODevice::ReadOnly)) {
return context->throwValue(QString("Failed to open %0").arg(moduleName));
}
QTextStream in(&file);
in.setCodec("UTF-8");
auto script = in.readAll();
file.close();
#if 0
// I had to disable this, because it barfs on "get not()" definition - is
// that a Node extension? Will it cause me problems even if I get require()
// working?
auto syntax_check = QScriptEngine::checkSyntax(script);
if (syntax_check.state() != QScriptSyntaxCheckResult::Valid) {
return context->throwValue(QString("%2:%0:%1: Syntax error: %3")
.arg(syntax_check.errorLineNumber())
.arg(syntax_check.errorColumnNumber())
.arg(filename, syntax_check.errorMessage()));
}
#endif
// create a new context, and capture the module's exports
QScriptContext* newContext = engine->pushContext();
QScriptValue exports = engine->newObject();
newContext->activationObject().setProperty("exports", exports);
module.setProperty("code", exports);
module.setProperty("filename", filename);
module.setProperty("timestamp", engine->newDate(QFileInfo(filename).lastModified()));
// run the script
engine->evaluate(script, filename);
// get the exports
module.setProperty("code", newContext->activationObject().property("exports"));
engine->popContext();
if (engine->hasUncaughtException())
return engine->uncaughtException();
qDebug() << "loaded" << moduleName;
return exports;
}
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
QScriptEngine engine;
// register global require() function
auto global = engine.globalObject();
global.setProperty("require", engine.newFunction(require));
global.setProperty("$MODULES", engine.newObject());
engine.evaluate("var should = require('/usr/lib/nodejs/should/lib/should');");
if (engine.hasUncaughtException()) {
qCritical() << engine.uncaughtException().toString().toStdString().c_str();
qWarning() << engine.uncaughtExceptionBacktrace().join("\n").toStdString().c_str();
return 1;
}
return 0;
}
生成文件
check: should
./should
CXXFLAGS += -std=c++11 -Wall -Wextra -Werror
CXXFLAGS += -fPIC
CXXFLAGS += $(shell pkg-config --cflags Qt5Script)
LDLIBS += $(shell pkg-config --libs Qt5Script)
输出是
require "/usr/lib/nodejs/should/lib/should"
require "./util"
require "./inspect"
found up-to-date module for require of "./util"
loaded "./inspect"
require "assert"
Failed to open assert
<eval>() at /usr/lib/nodejs/should/lib/./util.js:126
<native>() at -1
<native>('./util') at -1
<eval>() at /usr/lib/nodejs/should/lib/should.js:8
<native>() at -1
<native>('/usr/lib/nodejs/should/lib/should') at -1
<global>() at 1
(顺带一提 - 我如何在堆栈跟踪中获取实际函数名称 require
而不是 <native>
?槽管理这个,所以我应该能够,对吧?)
最佳答案
我已经对其进行了更详细的研究,重写 C++ Qt require system 对我来说比最初认为的要多一些时间。具有 require
核心模块的库也存在问题(反过来 require
native 模块会导致未定义的行为 - 阅读:可能行不通)。
方法 #1 - C++ require()
实现:
在 C++ Qt 中实现自定义 node
require()
就像它已在您的问题和链接中启动一样。 node.js
require()
的工作细节可见here .您需要在 require()
搜索路径中包含核心 node
模块(您可以从 node.js
源存储库中获取它们)。
方法 #2 - 使用 browserify
既然我们在 #1 中试图解决的问题基本上是加载和缓存 javascript 文件,为什么不使用已经存在的东西来达到同样的目的。通过这种方式,我们可以避免手动工作并捆绑 javascript
我们有强烈的迹象表明它可以在浏览器上运行(比 node.js
环境更有限)。
$ npm install -g browserify
$ npm install expect
index.js
var expect = require('expect');
expect(1).toEqual(1);
然后运行browserify
:
$ browserify index.js -o bundle.js
在你的Qt C++
中:
QString script = loadFile("/path/to/bundle.js");
engine.evaluate(script);
我们已经找到了 require()
的解决方法,但我不确定互操作性。使用 Qt
。此外,对于某些 js
模块,我在 QtScript 中遇到了一些Syntax Error
,因此即使乍一看它也不是 Elixir 。
注意:这也是一个有趣的项目:https://github.com/svalaskevicius/qtjs-generator .
关于c++ - 我可以将 should.js 与 QtScript 一起使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33936602/