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>
不能操作本地文件是挺无聊的… 不过也感觉不错了
不知道这个什么时候真是做出来么…
这个应该木有什么实用功能吧…
http://www.youtube.com/watch?v=gkb_x9ZN0Vo&feature=g-all-lsb Github 上翻到一个视频, 说可以在浏览器里直接调试 Node 代码 视频放着放着断了… 待会接着看
有更新… 哪位装的 Chrome Canary 有兴趣深入一下吗? Node.js in Chrome With Node-chromify
你的帖子内容提到的这个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这样的框架来创建桌面应用程序。