javascript - 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
从控制台。
任何帮助是极大的赞赏 :)
解决方案
推荐阅读
- arrays - 是否可以从列中的列表中加入或合并或合并值以生成动态公式
- c# - 使用 Json.net 自定义序列化
- c# - 从函数返回具有基类约束的泛型类型,而无需在 C# 中进行强制转换
- r - NA 如果值包含在 NA 之间
- r - 在 R 中使用 lapply 绘制多个数据帧
- javascript - Javascript未向php提交数据
- azure - 有没有办法实时监听 Azure AD B2C 中的事件
- sql - PostgreSQL - 列出带有消息“错误:d.daticu 列不存在”的数据库时出现错误
- typescript - 如何将类型附加到 Typescript 上全局可用的库
- amazon-web-services - aws-vault 实际用于什么?