-2

I want to run some javascript code from external source inside node.js server and return the results. inside html code I would just use

<script>http:\\address.of.code.com\code.js</script>

how do I run this inside node.js get the results of this script and return it to the caller ?

I have no prior knowledge of the script I want to run and it's resides in external address.

4
  • Possible duplicate of Node.js: calling pure Javascript functions Commented Apr 6, 2016 at 18:55
  • @abc123: Can require fetch remote files? Commented Apr 6, 2016 at 18:58
  • @abc123 yeah this is asking something a good bit different. I think in the link you posted the idea there is that the script is within the same context, so in Node's case that would normally mean the same fs. Commented Apr 6, 2016 at 19:09
  • need to run the script, not to fetch it Commented Apr 6, 2016 at 19:18

2 Answers 2

1

I suggest looking at Node's native vm module. So building on Nazar's example:

var vm = require('vm');
var request = require('request');
request('http://address.of.code.com/code.js', function (error, response, body) {
    if (!error && response.statusCode == 200) {
           var script = vm.Script(body);
           var ctxt = {};
           script.runInNewContext(ctxt);
           console.log(ctxt);
    }
});

This pulls the script from it's remote address and runs it without affecting the code pulling the script. Here are vm's docs: https://nodejs.org/dist/latest-v4.x/docs/api/vm.html

Sign up to request clarification or add additional context in comments.

4 Comments

@Dani thanks! Mind accepting the answer in that case?
sure, I still have an issue - b/c the scripts need to run inside a browser apparently (missing document ect...) but it's out of the scope of this question...
Oh that's probably because window === undefined in Node. If you look at vm's docs, you can define a context with global variables already defined, so you can define window as {} and it should be fine.
If it does UI stuff, yes, but in theory, using vm's context you could completely fake a dom. Although I could see replicating events in there becoming a big headache.
1

What about this?

    var request = require('request');
    request('http:\\address.of.code.com\code.js', function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(body) 
         }
    })

Best regards, Nazar Medeiros

1 Comment

This code get me the script but does not run it I'll try @Christian Grabowski enhancement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.