gpt4 book ai didi

html - 打包 NodeWebkit 和 Web 服务器

转载 作者:太空宇宙 更新时间:2023-11-04 00:45:57 25 4
gpt4 key购买 nike

我的应用程序已准备好分发,并且我决定要使用 NodeWebkit。现在的问题是我的应用程序加载本地文件,我需要一个网络服务器。如何将 NodeWebkit 和某些 Web 服务器打包在一起?如果无法将 Web 服务器添加到 NodeWebkit,我如何将我的文件(图像、脚本、css)加载到 html 中?谢谢! :)

setTimeout(function() {
var http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs"),
port = process.argv[2] || 8888;

var server = http.createServer(function(request, response) {

var uri = url.parse(request.url).pathname
, filename = path.join(process.cwd(), uri);

fs.exists(filename, function(exists) {
if(!exists) {
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
return;
}

if (fs.statSync(filename).isDirectory()) filename += '/index.html';

fs.readFile(filename, "binary", function(err, file) {
if(err) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
return;
}

response.writeHead(200);
response.write(file, "binary");
response.end();
});
});
}).listen(parseInt(port, 10));
}, 1000);

最佳答案

Node-webkit 基本上是 node.js 和 chromium 浏览器的组合。如果您想让您的应用程序拥有服务器,您可以在 Node 中编写服务器。

查看 Node 主documentation

在你的 package.json 中

{
"name": "nw-demo",
"node-main": "index.js",
"main": "index.html"
}

mode-main 基本上是一个在 node 中运行的脚本。上下文并随着应用程序启动而启动。

The script will be running in Node's context which won't be destroyed across page navigation in Webkit, so it can be used to write some 'background' or 'daemon' like code.

这样你就可以编写并开始你的 http服务器位于 127.0.0.1 本地并与之通信。

<小时/>

如果您只关心加载资源,您可以通过提供绝对或相对路径直接添加它们。

例如:

<link rel="stylesheet" type="text/css" href="/bower_components/angular-ui-grid/ui-grid.css"/>
<script src="/bower_components/jquery/dist/jquery.min.js"></script>
<小时/>

使用应用协议(protocol)

此外,nw.js 中提供了一个 app:// 协议(protocol),您可以使用它来本地访问文件。请参阅documentation .

注意:

The root of path refers to the application's directory, which is the directory where the manifest file resides.

关于html - 打包 NodeWebkit 和 Web 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34727628/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com