Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/visual-studio-2010/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Nodejs执行节点文件并获取其输出_Javascript_Node.js - Fatal编程技术网

Javascript Nodejs执行节点文件并获取其输出

Javascript Nodejs执行节点文件并获取其输出,javascript,node.js,Javascript,Node.js,我正在学习Node.js并制作一个Web服务器,我想做的是需要一个执行nodejs代码的文件,并将该文件的输出捕获到一个变量中。可能吗 我有以下资料: Main.js my_file.js 我希望Main.js的输出在web浏览器中显示Hello World,当我转到url时,它会显示在控制台中,但页面上实际显示的是console.logHello World 有没有办法让浏览器只显示Hello World而不显示实际代码 编辑 当我这样做时: http.createServer(functio

我正在学习Node.js并制作一个Web服务器,我想做的是需要一个执行nodejs代码的文件,并将该文件的输出捕获到一个变量中。可能吗

我有以下资料:

Main.js

my_file.js

我希望Main.js的输出在web浏览器中显示Hello World,当我转到url时,它会显示在控制台中,但页面上实际显示的是console.logHello World

有没有办法让浏览器只显示Hello World而不显示实际代码

编辑

当我这样做时:

http.createServer(function (request, response){
    // Stripped Code
    var child = require('child_process').fork(full_path, [], []);
    child.stdout.on('data', function(data){
        response.write(data);
    });
    // Stripped Code
}).listen(port, '162.243.218.214');
我得到以下错误:

child.stdout.on('data', function(data){
             ^
TypeError: Cannot call method 'on' of null
    at /home/rnaddy/example.js:25:38
    at fs.js:268:14
    at Object.oncomplete (fs.js:107:15)

我这样做不对吗?

我认为你处理事情的方式不对。如果您的最终目标是向浏览器写入内容,则根本不应该使用console.log。在my_file.js中,您只需要module.exports='Hello World'

这不是PHP,您可以在文件中写出内容,然后将该文件包含到浏览器的输出中

main.js my_file.js 我们走!我明白了

var child = require('child_process').fork(full_path, [], {silent: true});
child.stdout.on('data', function(data){
    response.write(data);
});
child.stdout.on('end', function(){
    response.end();
});

请看一下模块,尤其是。子进程的流可以是开放的。好吧,所以我可以分叉它,但我不确定如何获得流。。。如果你看到我的编辑,这是正确的方法吗?
child.stdout.on('data', function(data){
             ^
TypeError: Cannot call method 'on' of null
    at /home/rnaddy/example.js:25:38
    at fs.js:268:14
    at Object.oncomplete (fs.js:107:15)
var http = require('http');
var content = require('./my_file.js');

http.createServer(function(req, res) {
  res.end(content);
}).listen(port);
var content = '';
// build content here
module.exports = content;
var child = require('child_process').fork(full_path, [], {silent: true});
child.stdout.on('data', function(data){
    response.write(data);
});
child.stdout.on('end', function(){
    response.end();
});