一個web服務器發佈html文件,經過CGI接口,程序也能夠對請求/迴應數據流進行加工。那web服務器能夠發佈一個class類嗎?javascript
當你用nodejs在後端寫了一個class類,但願被前端或遠程其餘nodejs調用。這時你該怎麼辦?......還得一陣猛忙活,而後宣稱提供了一個什麼RESTful之類的接口。html
把class直接發佈行不行?就是在瀏覽器中或遠程其餘nodejs中直接調用,就像在你的後端直接調用一個模塊同樣。這就叫發佈一個class 類。前端
演示的例子固然叫HelloWorld了:-),這是慣例。java
編寫一個類HelloWorld.es6node
class HelloWorld { constructor() { this.greeting = 'Hello World!'; } welcome(callback) { callback(null, this.greeting); } } export default HelloWorld;
使用babel轉成ES5es6
$ babel HelloWorld.es6 -o HelloWorld.js
若是你還不會使用babel,那就使用babel官網轉吧!轉完的文件叫HelloWorld.jsweb
# npm install nodeway -g
安裝nodeway,這一步應該沒什麼可解釋的。能解釋的就是這個名字,還不想解釋。npm
使用nodeway命令,把你寫的HelloWorld這個類發佈出去吧!json
# nodeway --class HelloWorld.js --host 0.0.0.0 --port 8080 --docs . &
這句的意思是啓動一個Web Server,把HelloWorld.js發佈出去。
好了,如今剩下的就是測試了。後端
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>HelloWorld</title> <script type="text/javascript" src="/HelloWorld.js"></script> </head> <body> <script> var api = new HelloWorld.default; api.welcome(function(err, greeting) { document.write(greeting); }); </script> </body> </html>
用瀏覽器訪問你寫的這個index.html文件,就能夠看到你發佈成功了。
簡單吧?還能再簡單點不?能呀!若是你懶得安裝nodeway包,那就把下面內容貼到你的Web服務器下
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>HelloWorld</title> <script type="text/javascript" src="http://yishizhencang.com:8080/HelloWorld.js"></script> </head> <body> <script> var api = new HelloWorld.default; api.welcome(function(err, greeting) { document.write(greeting); }); </script> </body> </html>
這有什麼不一樣?原來<script>標籤中src變了!遠程執行我發佈的HelloWorld類?這是跨域訪問呀?這也能行?
固然沒問題了,你試試就知道了。
還有什麼新鮮的嗎?有啊!你能夠用node遠程調用HelloWorld類。vi welcome.js,寫以下代碼:
var requireFromUrl = require('require-from-url'); requireFromUrl("http://yishizhencang.com:8080/HelloWorld.js") .on('Resolved', function(next, HelloWorld) { var api = new HelloWorld.default; api.welcome(function(err, greeting) { console.log(greeting); }); }) .on('Rejected', function(next, e) { console.log(e); });
requireFromUrl是什麼?就是require!只不過是從URL中加載。
$ npm install require-from-url $ node welcome.js
以上這個例子,能夠經過以下命令下載
$ npm install nodeway-helloworld
nodeway同時支持json-rpc,這樣用其它語言訪問也是沒問題的。若是你有這方面的需求,就查看一下json-rpc的文檔,編寫個json-rpc客戶端程序就好了。