使用 Kotlin 创建简单的节点服务器

Creating simple Node server with Kotlin

我正在尝试使用 Kotlin 创建一个简单的节点服务器来复制基本示例 here:

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

所以,我做了以下操作:

新建文件夹,命名为node

使用 npm init

创建 npm package

使用此命令创建了新的 gradle projectgradle init --type java-library

删除了 src/mainsrc/test 文件夹

创建了 src/kotlinsrc/resources 文件夹

build.gradle 文件的内容替换为:

buildscript {
    ext.kotlin_version = '1.2.21'
    ext.node_dir = 'node'
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 
    }
}
apply plugin: 'kotlin2js'

repositories {     jcenter()    }

dependencies {
    def kotlinx_html_version = "0.6.8"
    compile "org.jetbrains.kotlin:kotlin-stdlib-js:$kotlin_version"
}

sourceSets.main {
   kotlin.srcDirs += 'src/kotlin'
   resources.srcDirs += 'src/resources'
}

compileKotlin2Js.kotlinOptions {
   outputFile = "${projectDir}/${node_dir}/index.js"
   moduleKind = "commonjs" 
   sourceMap = true
}

clean.doFirst() {
    delete("${node_dir}")
}

npm 安装 kotlin 作为本地版本:npm i kotlin 注意:全局安装它 npm i -g kotlin 根本不起作用。

注意:在将依赖项添加到 package.json 文件后,我还使用 npm installnpm i 完成了此操作,结果如下:

{
  "name": "kotlin-node-app",
  "version": "1.0.0",
  "description": "Node Application built with Kotlin Lang",
  "main": "index.js",
  "dependencies": {
    "kotlin": "^1.2.21"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "kotlin"
  ],
  "author": "Hasan Yousef",
  "license": "ISC"
}

src/kotlin/Main.Kt 创建了我的文件,如下所示:

external fun require(module:String):dynamic

fun main(args: Array<String>) {
    println("Hello JavaScript!")

    val http = require("http")
    val hostname = "127.0.0.1"
    val port = 3000

    println("Server will try to run at http://${hostname}:${port}/")

    val server = http.createServer{req, res -> 
        res.statusCode = 200
        res.setHeader("Content-Type", "text/plain")
        res.end("Hello World\n")
    }

    server.listen{port, hostname ->
       println("Server running at http://${hostname}:${port}/")
    }
}

使用 gradle build 构建项目并根据需要生成 index.js 文件。

曾经 运行 文件 node index.js 它没有工作,看起来应用程序在调用 [=38= 时没有读取 porthost 的值].

应用程序的结构、代码和输出在此屏幕截图中:

生成的index.js是:

(function (_, Kotlin) {
  'use strict';
  var println = Kotlin.kotlin.io.println_s8jyv4$;
  var Unit = Kotlin.kotlin.Unit;
  function main$lambda(req, res) {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    return res.end('Hello World\n');
  }
  function main$lambda_0(port, hostname) {
    println('Server running at http://' + hostname + ':' + port + '/');
    return Unit;
  }
  function main(args) {
    println('Hello JavaScript!');
    var http = require('http');
    var hostname = '127.0.0.1';
    var port = 3000;
    println('Server will try to run at http://127.0.0.1:3000/');
    var server = http.createServer(main$lambda);
    server.listen(main$lambda_0);
  }
  _.main_kand9s$ = main;
  main([]);
  Kotlin.defineModule('index', _);
  return _;
}(module.exports, require('kotlin')));

//# sourceMappingURL=index.js.map

刚找到,在调用server.listen

将语法视为 'server.listen(port, hostname, backlog, callback);'

Kotlin中应该是:

server.listen(port, hostname, fun() { 
    println("Server running at http://${hostname}:${port}/")
})

所以,下面的代码现在非常适合我:

external fun require(module:String):dynamic

fun main(args: Array<String>) {
    println("Hello JavaScript!")

    val http = require("http")
    val hostname = "127.0.0.1"
    val port = 3000

    println("Server will try to run at http://${hostname}:${port}/")

    val server = http.createServer{req, res -> 
        res.statusCode = 200
        res.setHeader("Content-Type", "text/plain")
        res.end("Hello World\n")
    }

    server.listen(port, hostname, fun() { 
        println("Server running at http://${hostname}:${port}/")
    })

    /* OR
    server.listen(port, hostname, {
       println("Server running at http://${hostname}:${port}/") } )
    */

   /* OR
    server.listen(port, hostname) {
      println("Server running at http://${hostname}:${port}/") }
   */
}

而生成的编译index.js文件是:

(function (_, Kotlin) {
  'use strict';
  var println = Kotlin.kotlin.io.println_s8jyv4$;
  function main$lambda(req, res) {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    return res.end('Hello World\n');
  }
  function main$lambda_0() {
    println('Server running at http://127.0.0.1:3030/');
  }
  function main(args) {
    println('Hello JavaScript!');
    var http = require('http');
    var hostname = '127.0.0.1';
    var port = 3030;
    println('Server will try to run at http://127.0.0.1:3030/');
    var server = http.createServer(main$lambda);
    server.listen(port, hostname, main$lambda_0);
  }
  _.main_kand9s$ = main;
  main([]);
  Kotlin.defineModule('index', _);
  return _;
}(module.exports, require('kotlin')));

//# sourceMappingURL=index.js.map

然后我运行它顺利地使用node node/index.js命令