首页 > 解决方案 > execSync 保持不变,不返回任何值

问题描述

我在一个类似 CodeCademy 的应用程序中工作,用户在其中输入一些代码并运行,然后结果显示在控制台中。为此,我创建了一个 express 环境,在网站中,用户可以键入他们的代码,然后通过 POST 请求发送它。

我的问题是以下代码:

const fs = require('fs');
const {execSync} = require('child_process')

function run(code) {
  var path = __dirname + '/../temp/temp.js';
  fs.writeFileSync(path, code);
  console.log('file written');
  let out = execSync('node ' + path); // code stays put
  console.log('file executed') // does not happen
  return out.toString();
}

module.exports = {
  run: run
};

我将用户输入写入 temp.js 文件,然后我计划使用 execSync 执行该文件。第一个 console.log 被执行,第二个没有。

我从以下路线调用它:

router.post('/', (req, res, next) => {
  res.render('index', {
    instructions: reader.readInstructions('lesson1.txt'),
    console: runner.run(req.body.editor) 
  })
})

这个问题的奇怪之处在于这段代码:

const fs = require('fs');
const {execSync} = require('child_process')

String code = 'var a = 0\nvar b = 5\nconsole.log(a*b)';

fs.writeFileSync('../temp/temp.js', 'code');
let out = execSync('node ../temp/temp.js');
console.log(out.toString());

如果我使用命令运行它,则按预期工作(返回字符串的值)

node runner.js

从控制台。

任何帮助是极大的赞赏 :)

标签: javascriptnode.jsexpress

解决方案


推荐阅读