介绍
一般情况下,atom-shell可以让你使用纯的javascript来创建桌面应用程序,并提供了丰富的运行时原生API。你可以把它看成Node.js的运行时,但是面向的不是web server,而是桌面应用程序。
这不是说atom-shell是绑定了GUI库的javascript。而是使用web页面作为它的GUI,所以你可以把它当成一个小型的chromium浏览器,被javascript控制。
浏览器端
如果你有使用Node.js开发web应用程序的经验,那么你会知道这里有两种javascript脚本,服务器端脚本和客户端的脚本,服务器端是运行在Node.js上的,客户端的是运行在用户的浏览器的。在atom-shell中,我们有同样的概念,因为我们使用web页面来作为GUI,所以我们有运行在web页面上的脚本和运行在atom-shell运行时的脚本,这些脚本创建这些页面。类似Node.js,我们叫他们客户脚本和浏览器脚本 (意思是,浏览器取代了服务器的概念)。
在传统的Node.js程序,服务端和客户端通信主要是通过web sockets。在atom-shell, 我们提供了ipc作为之间的通信模块,还有支持远程RPC调用的远程模块。
Web页面和Node.js
通常情况下web页面设计成不能访问浏览器之外的东西,这样使得他们和宿主系统的交互很不舒服(不方便)。Atom-shell在web页面提供了Node.js的API,这样你就可以在web页面访问系统级的资源,就像node-webkit。
但是和node-webkit不同的是,你不能在web页面做类似原生GUI那样相关的操作,你需要在浏览器端通过发送消息来做这件事,或者使用远程模块。
写第一个atom-shell程序
通常情况下,一个atom-shell程序的结构应该是这样的(参见 hello-atom:
your-app/
├── package.json
├── main.js
└── index.html
package.json
的格式和Node的模块格式一模一样,main.js
是程序入口,它运行在浏览器端,你的package.json
可能是这样的:
{
"name" : "your-app",
"version" : "0.1.0",
"main" : "main.js"
}
main.js
应该创建城口,并处理系统消息,典型的例子像这样:
var app = require('app'); // Module to control application life.
var BrowserWindow = require('browser-window'); // Module to create native browser window.
// Report crashes to our server.
require('crash-reporter').start();
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the javascript object is GCed.
var mainWindow = null;
// Quit when all windows are closed.
app.on('window-all-closed', function() {
if (process.platform != 'darwin')
app.quit();
});
// This method will be called when atom-shell has done everything
// initialization and ready for creating browser windows.
app.on('ready', function() {
// Create the browser window.
mainWindow = new BrowserWindow({width: 800, height: 600});
// and load the index.html of the app.
mainWindow.loadUrl('file://' + __dirname + '/index.html');
// Emitted when the window is closed.
mainWindow.on('closed', function() {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
});
});
这里index.html
是你想显示的web页面:
<!DOCTYPE html>
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
We are using node.js <script>document.write(process.version)</script>
and atom-shell <script>document.write(process.versions['atom-shell'])</script>.
</body>
</html>
运行你的程序
当你完成了你的app,你可以通过程序分发指南常见一个程序包,然后运行这个程序包。
你也可以使用下载好的atom-shell二进制来直接执行你的app。
在windows:
$ .\atom-shell\atom.exe your-app\
在Linux:
$ ./atom-shell/atom your-app/
在Mac OS X:
$ ./Atom.app/Contents/MacOS/Atom your-app/
Atom.app
是atom-shell的发型包里面的一部分,你可以在这里下载。