2014-10-31 37 views
-2

我正在学习Node.js和制作网络服务器,我想做的是require()一个执行nodejs代码并将文件输出捕获到变量中的文件。那可能吗?Nodejs执行节点文件并得到它的输出

我有以下:

Main.js

// Webserver code above 
require('my_file.js'); 
// Webserver code below 

my_file.js

console.log("Hello World"); 

我想Main.js的输出,以显示Hello World在网络浏览器中,它显示y在控制台,当我去的网址,但实际显示在页面上是什么console.log("Hello 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) 

我这不是正确的这样做呢?

+0

查看[child process](http://nodejs.org/api/child_process.html)模块,特别是['fork()'](http://nodejs.org/api /child_process.html#child_process_child_process_fork_modulepath_args_options)。子流程的['stdout'](http://nodejs.org/api/child_process.html#child_process_child_stdout)可以[流](http://nodejs.org/api/stream.html)打开['http.ServerResponse'](http://nodejs.org/api/http.html#http_class_http_serverresponse)。 – 2014-10-31 19:41:12

+0

好的,所以我能够fork()它,但我不知道如何获取流...如果您看到我的编辑,是否正确的方法来做到这一点? – 2014-10-31 20:18:12

+0

http://stackoverflow.com/questions/22275556/node-js-forked-pipe – AJcodez 2014-10-31 20:39:03

回答

0

在这里,我们走!我知道了!

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(); 
}); 
0

我认为你正在接近错误的方式。如果您的最终目标是向浏览器写入内容,则根本不应该使用console.log。所有你需要在my_file.jsmodule.exports = 'Hello World';

这不是PHP,你会写出一个文件的东西,然后包括该文件,以包括它在输出到浏览器。

main.js

var http = require('http'); 
var content = require('./my_file.js'); 

http.createServer(function(req, res) { 
    res.end(content); 
}).listen(port); 

my_file.js

var content = ''; 
// build content here 
module.exports = content;