Nodejs:用 Chrome 扩展来跑 Node 程序

Nodejs:用 Chrome 扩展来跑 Node 程序

有点标题党, Github 上看到一个 repo, 里面只有文档, 没有代码 - -! https://github.com/arunoda/chrome-node 之前有新闻说 Chrome 的 extension 里能监听 TCP 端口了 https://github.com/GoogleChrome/chrome-app-samples/tree/master/webserver 看更早的新闻, UDP 估计也在计划当中, 不知道现在消息怎么样了… http://blog.alexmaccaw.com/chrome-tcp-udp 然后这个 repo 里说用 Chrome 来跑 Node, 我听着感觉很帅啊

<!doctype html>
<html>
    <head>
        <script type="text/javascript" src='node.js'></script>
        <script type="text/javascript">

            var http = require('http');
            http.createServer(function (req, res) {
                res.writeHead(200, {'Content-Type': 'text/plain'});
                res.end('Hello World\n');
            }).listen(1337, '127.0.0.1');
            console.log('Server running at http://127.0.0.1:1337/');

        </script>
    </head>
</html>

不能操作本地文件是挺无聊的… 不过也感觉不错了

不知道这个什么时候真是做出来么…


6 回复

标题:Nodejs:用 Chrome 扩展来跑 Node 程序

内容:

最近在 GitHub 上看到一个名为 chrome-node 的仓库(链接),这个仓库只包含了文档,并没有实际的代码。这让我感到有些失望,不过它的想法却非常有趣。

此外,我还发现 Chrome 扩展程序已经支持监听 TCP 端口了。你可以查看以下仓库了解具体实现方式(链接)。更早的报道还提到,Chrome 可能会支持 UDP 端口,但目前还不确定这一功能是否已经实现(链接)。

这个 chrome-node 项目声称可以在 Chrome 中运行 Node.js 程序,听起来确实非常酷!

示例代码

下面是一个简单的示例代码,展示了如何在浏览器中使用 JavaScript 模拟 Node.js 的 HTTP 服务器行为:

<!DOCTYPE html>
<html>
<head>
    <script>
        // 模拟 Node.js 的 require 函数
        function require(module) {
            if (module === 'http') {
                return {
                    createServer: function (callback) {
                        return {
                            listen: function (port, host) {
                                console.log(`Server running at http://${host}:${port}/`);
                                window.addEventListener('fetch', function (event) {
                                    const request = event.request;
                                    callback(request, {
                                        writeHead: function (status, headers) {
                                            event.respondWith(new Response('Hello World\n', {headers}));
                                        },
                                        end: function (data) {}
                                    });
                                });
                            }
                        };
                    }
                };
            }
        }

        // 创建 HTTP 服务器
        var http = require('http');
        http.createServer(function (req, res) {
            res.writeHead(200, {'Content-Type': 'text/plain'});
            res.end('Hello World\n');
        }).listen(1337, '127.0.0.1');
    </script>
</head>
<body>
</body>
</html>

解释

上述代码模拟了 Node.js 的 requirehttp 模块的功能。通过监听浏览器的 fetch 事件来模拟 HTTP 请求,并响应这些请求。这样,我们就可以在浏览器环境中模拟出一个简单的 HTTP 服务器。

尽管这种方式并不能完全替代 Node.js 的功能,特别是在处理本地文件系统方面,但它确实提供了一种在浏览器环境中执行类似 Node.js 逻辑的方法。

希望未来能够看到更多关于 Chrome 扩展和 Node.js 结合的新特性!


这个应该木有什么实用功能吧…

http://www.youtube.com/watch?v=gkb_x9ZN0Vo&feature=g-all-lsb Github 上翻到一个视频, 说可以在浏览器里直接调试 Node 代码 视频放着放着断了… 待会接着看

有更新… 哪位装的 Chrome Canary 有兴趣深入一下吗? Node.js in Chrome With Node-chromify

更新频率和bug伤不起的版本

你的帖子内容提到的这个repo(https://github.com/arunoda/chrome-node)实际上是将Node.js代码嵌入到Chrome扩展中执行。不过目前这个repo并没有提供具体的实现代码,只是提供了概念验证文档。

当前版本的Chrome扩展并不支持直接运行Node.js代码,因为Node.js代码需要使用一些浏览器不支持的API(如文件系统操作等)。但是,可以使用一些技术来模拟这些功能,比如使用IndexedDB来代替文件系统。

这里展示一个简单的示例,说明如何在Chrome扩展中运行Node.js代码片段。实际情况下,这种方法并不完全等同于原生Node.js环境,但可以用来理解如何在Chrome扩展中执行JavaScript代码:

示例代码

首先创建一个简单的manifest.json文件:

{
  "manifest_version": 2,
  "name": "Node.js in Chrome Extension",
  "version": "1.0",
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  }
}

然后创建一个background.js文件,其中包含一些模拟Node.js的代码:

// background.js
console.log('Extension Background Script Running...');

// 这里我们可以写一些模拟Node.js的代码
function simulateNodeJSCode() {
  // 模拟require
  const modules = {
    http: {
      createServer: function(callback) {
        return {
          listen: function(port, host) {
            callback();
            console.log(`Server listening on ${host}:${port}`);
          }
        };
      },
      IncomingMessage: class {},
      ServerResponse: class {}
    }
  };

  // 模拟创建HTTP服务器
  const http = modules.http;
  http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello World\n');
  }).listen(1337, '127.0.0.1');

  console.log('Simulated HTTP server started.');
}

simulateNodeJSCode();

请注意,这只是一个简化的示例,用于演示如何在Chrome扩展中模拟Node.js的行为。在实际应用中,你需要处理更多复杂的细节,如异步操作、网络请求等。

如果你想要真正地运行完整的Node.js程序,建议使用Node.js本身或者使用类似Electron这样的框架来创建桌面应用程序。

回到顶部