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

Nodejs execute node file and get its output

本文关键字:获取 输出 文件 执行 节点 Nodejs      更新时间:2023-09-26

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

我有以下内容:

Main.js

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

my_file.js

console.log("Hello World");

我希望Main.js的输出在web浏览器中显示Hello World,当我转到url时,它确实会显示在控制台中,但页面上实际显示的是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)

我这样做不对吗?

我认为你处理事情的方式不对。如果你的最终目标是向浏览器中写入一些内容,那么你根本不应该使用console.log。在my_file.js中,您只需要module.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;

开始吧!我明白了!

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