Support exports.main for simple files. (#165)
diff --git a/core/nodejsActionBase/runner.js b/core/nodejsActionBase/runner.js
index 25cdc6c..43f758b 100644
--- a/core/nodejsActionBase/runner.js
+++ b/core/nodejsActionBase/runner.js
@@ -53,8 +53,17 @@
})
.catch(error => Promise.reject(error));
} else try {
- // The code is a plain old JS file.
- let handler = eval('(function(){' + message.code + '\nreturn ' + message.main + '})()');
+ let handler = eval(
+ `(function(){
+ ${message.code}
+ try {
+ return ${message.main}
+ } catch (e) {
+ if (e.name === 'ReferenceError') {
+ return module.exports.${message.main} || exports.${message.main}
+ } else throw e
+ }
+ })()`);
return assertMainIsFunction(handler, message.main);
} catch (e) {
return Promise.reject(e);
diff --git a/tests/src/test/scala/runtime/actionContainers/NodeJsActionContainerTests.scala b/tests/src/test/scala/runtime/actionContainers/NodeJsActionContainerTests.scala
index 4122309..1f58fcb 100644
--- a/tests/src/test/scala/runtime/actionContainers/NodeJsActionContainerTests.scala
+++ b/tests/src/test/scala/runtime/actionContainers/NodeJsActionContainerTests.scala
@@ -344,6 +344,51 @@
}
}
+ it should "support exports.main for single files" in {
+ val (out, err) = withNodeJsContainer { c =>
+ val code =
+ """
+ | exports.main = function (params) {
+ | return params
+ | }
+ """.stripMargin
+
+ c.init(initPayload(code))._1 should be(200)
+ val (runCode, out) = c.run(runPayload(JsObject("payload" -> JsString("Hello exports!"))))
+
+ runCode should be(200)
+ out should be(Some(JsObject("payload" -> JsString("Hello exports!"))))
+ }
+
+ checkStreams(out, err, {
+ case (o, e) =>
+ o shouldBe empty
+ e shouldBe empty
+ })
+ }
+
+ it should "support module.exports.main for single files" in {
+ val (out, err) = withNodeJsContainer { c =>
+ val code =
+ """
+ | module.exports.main = function (params) {
+ | return params
+ | }
+ """.stripMargin
+
+ c.init(initPayload(code))._1 should be(200)
+ val (runCode, out) = c.run(runPayload(JsObject("payload" -> JsString("Hello exports!"))))
+
+ runCode should be(200)
+ out should be(Some(JsObject("payload" -> JsString("Hello exports!"))))
+ }
+
+ checkStreams(out, err, {
+ case (o, e) =>
+ o shouldBe empty
+ e shouldBe empty
+ })
+ }
it should "error when requiring a non-existent package" in {
// NPM package names cannot start with a dot, and so there is no danger
// of the package below ever being valid.