我有使用phantomjs
创建的脚本文件var webPage = require('webpage');
var page = webPage.create();
page.open(URL, function (status) {
var content = page.content;
console.log('Content: ' + content);
phantom.exit();
});
现在我想在Java程序中使用这个脚本,但我不能。 我在我的项目中这样做
ScriptEngineManager s = new ScriptEngineManager();
ScriptEngine se = s.getEngineByName("JavaScript");
se.eval(new FileReader("myScript.js"));
但是`这是结果
Exception in thread "main" javax.script.ScriptException: sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "require" is not defined. (<Unknown source>#1) in <Unknown source> at line number 1
at com.sun.script.javascript.RhinoScriptEngine.eval(RhinoScriptEngine.java:224)
at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:249)
at provaJavaScript.Client.main(Client.java:15)
Caused by: sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "require" is not defined. (<Unknown source>#1)
at sun.org.mozilla.javascript.internal.ScriptRuntime.constructError(ScriptRuntime.java:3770)
at sun.org.mozilla.javascript.internal.ScriptRuntime.constructError(ScriptRuntime.java:3748)
at sun.org.mozilla.javascript.internal.ScriptRuntime.notFoundError(ScriptRuntime.java:3833)
at sun.org.mozilla.javascript.internal.ScriptRuntime.getNameFunctionAndThis(ScriptRuntime.java:2218)
at sun.org.mozilla.javascript.internal.Interpreter.interpretLoop(Interpreter.java:1510)
at sun.org.mozilla.javascript.internal.Interpreter.interpret(Interpreter.java:849)
at sun.org.mozilla.javascript.internal.InterpretedFunction.call(InterpretedFunction.java:162)
at sun.org.mozilla.javascript.internal.ContextFactory.doTopCall(ContextFactory.java:430)
at com.sun.script.javascript.RhinoScriptEngine$1.superDoTopCall(RhinoScriptEngine.java:116)
at com.sun.script.javascript.RhinoScriptEngine$1.doTopCall(RhinoScriptEngine.java:109)
at sun.org.mozilla.javascript.internal.ScriptRuntime.doTopCall(ScriptRuntime.java:3160)
at sun.org.mozilla.javascript.internal.InterpretedFunction.exec(InterpretedFunction.java:173)
at sun.org.mozilla.javascript.internal.Context.evaluateReader(Context.java:1169)
at com.sun.script.javascript.RhinoScriptEngine.eval(RhinoScriptEngine.java:214)
... 2 more
我该怎么办?
编辑: 我把这一行放在我的代码中:
Process process = Runtime.getRuntime().exec("/usr/bin/phantomjs myScript.js");
但这不起作用。 progrma返回与以前相同的错误。 我该怎么办?
答案 0 :(得分:1)
要求不是标准javascript的一部分,而是NodeJS的一项功能。你的JAVA程序不知道如何处理它。
另见这个问题及其接受的答案:
答案 1 :(得分:1)
脚本引擎无法访问PhantomJS / nodejs添加到JavaScript的对象(require)
您可以使用exec
执行幻像。像
// You need the correct path for phantomJs
Process process = Runtime.getRuntime().exec("/usr/bin/phantomjs myScript.js");