2013-05-26 56 views
0

我正在使用Node Restify模塊創建接受POST的REST服務。在服務中,我嘗試使用Node Sandbox模塊創建一個沙盒進程,因爲我們將運行動態插入的Javascript,如果出現問題,我不希望它影響主節點實例。Node.JS在REST服務中運行Sandbox

當我嘗試創建沙箱時,出現了一些問題,導致REST服務恢復爲空。

這裏是我的代碼

var restify = require('restify'); 
var Sandbox = require("sandbox"); 
var logic; 

function createSandbox(body) { 
    var s = new Sandbox(); 
    s.run("1 + 1", function(output) { 
     logic = body.names + " has " + output.result; 
    }); 
} 

function respond(req, res, next) { 
    createSandbox(req.body); 
    res.send(logic); 
} 
var server = restify.createServer(); 
server.use(restify.bodyParser({ 
    mapParams: false 
})); 
server.post('/hello/:name', respond); 
server.head('/hello/:name', respond); 

server.listen(8080, function() { 
    console.log('%s listening at %s', server.name, server.url); 
}); 

在我的http請求我在身體{"names":"rob"}

我期待下面的響應

rob has 2 

-------- ---- UPDATE ------------------- This works

var restify = require('restify'); 
var Sandbox = require("sandbox"); 
var logic; 

function respond(req, res, next) { 
    var s = new Sandbox(); 
    s.run("1 + 1", function(output) { 
     logic = req.body.names + " has " + output.result; 
     res.send(logic); 
    }); 
} 
var server = restify.createServer(); 
server.use(restify.bodyParser({ 
    mapParams: false 
})); 
server.post('/run/:id', respond); 
server.head('/run/:id', respond); 

server.listen(8080, function() { 
    console.log('%s listening at %s', server.name, server.url); 
}); 

回答

0

Sandbox.run()是異步的。它只是將沙箱設置爲稍後運行,並在沙箱代碼實際運行之前立即返回,因此在設置之前您正在讀取logic

快速演示;

var Sandbox = require("sandbox"); 

function createSandbox() { 
    var s = new Sandbox(); 
    s.run("1 + 1", function(output) { 
     console.log("inside"); 
    }); 
} 

createSandbox(); 
console.log("outside"); 

> outside 
> inside 
+0

賓果!謝謝。 – Rob