Running a javascript function in node.js

187 views
Skip to first unread message

Rohit Harchandani

unread,
Jul 23, 2014, 7:46:56 PM7/23/14
to nod...@googlegroups.com
Hi, I have just started playing around with node.js for a project. I parsed a JSON object which had a javascript function and when I tried to execute the function on the node.js server, I kept getting this error:
ReferenceError: require is not defined
I am sure i parsed the JSON object correctly to get the function, but not sure how to run this function. 
Thanks,
Rohit

Paul Spaulding

unread,
Jul 24, 2014, 8:30:30 AM7/24/14
to nod...@googlegroups.com
You can attach functions to an Object in JavaScript, but you cannot serialize/deserialize functions inside JavaScript Objects using JSON (at least not without extra meta-programming).  Functions are not one of the basic JSON types (Number, String, Boolean, Array, Object, null).

var a = {foo: function () {console.log('Hello');}};
JSON
.stringify(a); // yields "{}"

Jose Luis Rivas

unread,
Jul 24, 2014, 11:23:38 AM7/24/14
to nod...@googlegroups.com
'require' is not defined. I think it's pretty clear.

If you show what the function does it may be easier but if I were you I
would be looking, in the meantime, where in the function I'm using
require and if I'm using it right.
> --
> Job board: http://jobs.nodejs.org/
> New group rules:
> https://gist.github.com/othiym23/9886289#file-moderation-policy-md
> Old group rules:
> https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
> ---
> You received this message because you are subscribed to the Google
> Groups "nodejs" group.
> To unsubscribe from this group and stop receiving emails from it, send
> an email to nodejs+un...@googlegroups.com
> <mailto:nodejs+un...@googlegroups.com>.
> To post to this group, send email to nod...@googlegroups.com
> <mailto:nod...@googlegroups.com>.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/nodejs/41c90927-ff6f-417d-abe2-5752492e2c47%40googlegroups.com
> <https://groups.google.com/d/msgid/nodejs/41c90927-ff6f-417d-abe2-5752492e2c47%40googlegroups.com?utm_medium=email&utm_source=footer>.
> For more options, visit https://groups.google.com/d/optout.

--
Jose Luis Rivas - http://joseluisrivas.net
Venezuela - GPG: 0xB9AC8C43

Ryan Schmidt

unread,
Jul 24, 2014, 11:23:55 AM7/24/14
to nod...@googlegroups.com
The JSON format does not accommodate functions, only data.

Perhaps you should show us some code so that we can more easily understand the problem you're encountering.

Rohit Harchandani

unread,
Jul 24, 2014, 1:09:19 PM7/24/14
to nod...@googlegroups.com
Hi,
This is the code that I am using to parse the JSON string.

var recData = JSON.parse(recDataString, function (key, value) {

    if (value && (typeof value === 'string') && value.indexOf("function") === 0) {

        var jsFunc = new Function('return ' + value)();

        return jsFunc;

    }

    return value;

});

console.log( "Type: " + typeof recData["runFunction"] )


runFunction in the json is a function which is something like this:


function() {

    require("fs");




--
Job board: http://jobs.nodejs.org/
New group rules: https://gist.github.com/othiym23/9886289#file-moderation-policy-md
Old group rules: https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
---
You received this message because you are subscribed to the Google Groups "nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email to nodejs+un...@googlegroups.com.
To post to this group, send email to nod...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/nodejs/B5AA737B-3074-4B3C-9551-F1AB89DA6941%40ryandesign.com.

Rohit Harchandani

unread,
Jul 24, 2014, 1:09:34 PM7/24/14
to nod...@googlegroups.com
Sorry, I sent the msg without completing it, but the function gets parsed correctly, but i am not able to execute the function. Not sure why require should be undefined?

Conrad Pankoff

unread,
Jul 24, 2014, 11:43:41 PM7/24/14
to nod...@googlegroups.com
This is almost definitely a very, very bad idea. Instead of trying to serialise your code into JSON, you can just put it in a regular JavaScript file and require() it. For example, instead of this:

// code.json
{"myFunction":"function(a) { console.log(a); }"}

var code = JSON.parse(fs.readFileSync("./code.json"));
/* magic, insecure function stuff from your post */
code
.myFunction("hello");

Do this:

// code.js
exports
.myFunction = function(a) { console.log(a); }

var code = require("./code.js");
/* look ma, no magic */
code.myFunction("hello");

I shudder to think of why you might be doing things the way you are - are you trying to fetch code from somewhere else and run it?

Rebecca Turner

unread,
Jul 25, 2014, 11:43:42 AM7/25/14
to nod...@googlegroups.com, Rohit Harchandani
I think that there's a syntax error in the source to the function you're passing in, because your code works for me.

var recDataString = JSON.stringify({
    function: 'function () {var fs = require("fs"); console.log("did stuff") }'
});
var recData = JSON.parse(recDataString, function (key,value) {
    if (value && (typeof value === 'string') && value.indexOf("function") === 0) {
        var jsFunc = new Function('return ' + value)();
        return jsFunc;
    }
    return value;
});

> recData
{ function: [Function] }
> recData.function();
did stuff
undefined

And:


var recData = JSON.parse(recDataString, function (key, value) {

    if (value && (typeof value === 'string') && value.indexOf("function") === 0) {

        var jsFunc = new Function('return ' + value)();

        return jsFunc;

    }

    return value;

});

console.log( "Type: " + typeof recData["runFunction"] )


runFunction in the json is a function which is something like this:


But "runFunction".indexOf("function") !== 0, so it'll never be inflated.

-- Rebecca

Ryan Schmidt

unread,
Jul 25, 2014, 11:43:49 AM7/25/14
to nod...@googlegroups.com
On Jul 24, 2014, at 11:18 AM, Rohit Harchandani <rha...@gmail.com> wrote:

> Hi,
> This is the code that I am using to parse the JSON string.
>
> var recData = JSON.parse(recDataString, function (key, value) {
> if (value && (typeof value === 'string') && value.indexOf("function") === 0) {
> var jsFunc = new Function('return ' + value)();
> return jsFunc;
> }
> return value;
> });
>
> console.log( "Type: " + typeof recData["runFunction"] )
>
> runFunction in the json is a function which is something like this:
>
> function() {
> require("fs");


Could you show us sample json input? It's much easier for us to help you if you give us enough information to easily reproduce the problem on our own systems.



Rohit Harchandani

unread,
Jul 25, 2014, 8:31:05 PM7/25/14
to nod...@googlegroups.com
@Conrad - yes, i am trying this out on the same node.js server now. but eventually the goal is to ship the code to a node.js client where the sent code could run. Earlier I did write it to a file and then 'require' it. That obviously works. Are there better methods of doing this? 

@Ryan - This is a simpler json string example below. This too does not work for me when i run: recData["runFunction"]();

{"runFunction":"function(){'use strict';\nvar net = require(\"net\");\n\nconsole.log(\"NET\");\n}"}





--
Job board: http://jobs.nodejs.org/
New group rules: https://gist.github.com/othiym23/9886289#file-moderation-policy-md
Old group rules: https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
---
You received this message because you are subscribed to the Google Groups "nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email to nodejs+un...@googlegroups.com.
To post to this group, send email to nod...@googlegroups.com.

Rebecca Turner

unread,
Jul 27, 2014, 12:32:17 PM7/27/14
to nod...@googlegroups.com, Rohit Harchandani

Rohit,
@Ryan - This is a simpler json string example below. This too does not work for me when i run: recData["runFunction"]();

{"runFunction":"function(){'use strict';\nvar net = require(\"net\");\n\nconsole.log(\"NET\");\n}"}

Try it yourself on the console as I do here and see what you get. I say this because I don't see any problems, see below. Or, alternatively, maybe you need to be clearer about what you mean by "does not work".

> var recDataString = JSON.stringify({
... "runFunction": "function(){'use strict';\nvar net = require(\"net\");\n\nconsole.log(\"NET\");\n}"
... });
> var recData = JSON.parse(recDataString, function (key,value) {
... if (value && (typeof value === 'string') && key.indexOf("runFunction") === 0) {
..... return new Function('return ' + value)();
..... }
... return value;
... });
> recData
{ runFunction: [Function] }
> recData["runFunction"]()
NET
>  

Alex Kocharin

unread,
Jul 27, 2014, 12:33:21 PM7/27/14
to nod...@googlegroups.com
 
```
var func = vm.runInNewContext('(function(){\'do not use strict\';\nvar net = require(\"net\");\n\nconsole.log(\"NET\");\n})', {require: require, console: console})
func()
```
 
That said, passing require to external code is unsafe, so you'll probably want to whitelist modules that code is allowed to require.
 
 
26.07.2014, 04:30, "Rohit Harchandani" <rha...@gmail.com>:
To view this discussion on the web visit https://groups.google.com/d/msgid/nodejs/CAMu3Ni1e34zRjv63B%2B49TKqzR783WtjaY99y3V7vUjmNTOTM3w%40mail.gmail.com.
Reply all
Reply to author
Forward
0 new messages