-3

I am learning Node.js and making a webserver, and what I would like to do, is to require() a file that executes nodejs code and capture that output of the file into a variable. is that possible?

I have the following:

Main.js

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

my_file.js

console.log("Hello World");

I would like the output of Main.js to display Hello World in a web browser, it does display in the console when I go to the url, but what is actually displaying on the page is console.log("Hello World");

Is there any way I can get the browser to display just the Hello World and not the actual code?

Edit

When I do this:

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');

I get the following error:

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)

Am I not doing this correctly?

just somebody
  • 18,602
  • 6
  • 51
  • 60
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
  • Have a look at the [child process](http://nodejs.org/api/child_process.html) module, especially [`fork()`](http://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options). The [`stdout`](http://nodejs.org/api/child_process.html#child_process_child_stdout) of a child process can be [streamed](http://nodejs.org/api/stream.html) to an open [`http.ServerResponse`](http://nodejs.org/api/http.html#http_class_http_serverresponse). – Jonathan Lonowski Oct 31 '14 at 19:41
  • Okay so I was able to fork() it, but I am not sure how to get the stream... If you see my edit, is that the correct way to do it? – Get Off My Lawn Oct 31 '14 at 20:18
  • http://stackoverflow.com/questions/22275556/node-js-forked-pipe – AJcodez Oct 31 '14 at 20:39

2 Answers2

0

I think you're approaching things the wrong way. If your end goal is to write something to a browser, you shouldn't be using console.log at all. All you would need in my_file.js is module.exports = 'Hello World';

This isn't PHP where you would write things out in a file, then include that file to include it in the output to the browser.

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;
Timothy Strimple
  • 22,920
  • 6
  • 69
  • 76
0

Here we go! I got it!

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();
});
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338