Skip to content

Instantly share code, notes, and snippets.

@asm256
Last active December 8, 2017 00:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asm256/d20bace8b4315340cebfb2bb2376d320 to your computer and use it in GitHub Desktop.
Save asm256/d20bace8b4315340cebfb2bb2376d320 to your computer and use it in GitHub Desktop.
Nashornを利用してローカルなウェブサーバーを建てる
rem:/*
@rem JavaScriptで作るWebサーバ
@rem via: http://tc.hatenablog.com/entry/2013/01/17/211851
@rem Windowsのバッチファイルにjjs scriptを書く
@rem via: https://qiita.com/tiibun/items/954580a1d840d5392032
@start http://localhost:8081/
@"%JAVA_HOME%\bin\jjs" -scripting "%~f0" %*
@exit /b %ERRORLEVEL%
*/
load("nashorn:mozilla_compat.js");
importClass(com.sun.net.httpserver.HttpExchange);
importClass(com.sun.net.httpserver.HttpHandler);
importClass(com.sun.net.httpserver.HttpServer);
importClass(java.io.File);
importClass(java.io.IOException);
importClass(java.io.InputStream);
importClass(java.io.OutputStream);
importClass(java.io.PrintWriter);
importClass(java.net.InetSocketAddress);
importClass(java.util.HashMap);
importClass(java.util.Map);
var PORT = 8081;
var DOCUMENT_ROOT = ".";
var contentTypes = new HashMap();
contentTypes.put("html", "text/html");
contentTypes.put("jpg", "image/jpeg");
contentTypes.put("png", "image/png");
contentTypes.put("gif", "image/gif");
contentTypes.put("css", "text/css");
contentTypes.put("js", "text/javascript");
var root = new File(DOCUMENT_ROOT);
var server = HttpServer.create(new InetSocketAddress("localhost", PORT), 0);
server.createContext("/", new HttpHandler({
handle : function(he) {
var path = he.getRequestURI().getPath();
var f = new File(root, path);
if(!f.exists()){
//ファイルがない
he.sendResponseHeaders(404, 0);
sendMessage(he.getResponseBody(), "not found.");
return;
}
if(f.isDirectory()){
var indexFile = new File(f, "index.html");
if(!indexFile.exists()){
he.sendResponseHeaders(403, 0);
sendMessage(he.getResponseBody(), "fobbiden.");
return;
}
f = indexFile;
}
var idx = path.lastIndexOf(".");
if(idx >= 0){
var ext = path.substring(idx + 1);
if(contentTypes.containsKey(ext)){
he.getResponseHeaders().add(
"Content-Type", contentTypes.get(ext));
}
}
he.sendResponseHeaders(200, f.length());
var is = new java.io.FileInputStream(f);
var res = he.getResponseBody();
var buf = java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, 1024);
var len;
while((len = is.read(buf)) >= 0){
res.write(buf, 0, len);
}
res.close();
is.close();
}
}));
server.start();
function sendMessage(res, message) {
var pw = new PrintWriter(res);
pw.println(message);
pw.close();
res.close();
}
java.lang.Thread.currentThread().suspend();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment