【问题标题】:Creating simple Node server with Kotlin使用 Kotlin 创建简单的 Node 服务器
【发布时间】:2018-07-28 04:20:46
【问题描述】:

我正在尝试使用 Kotlin 创建一个简单的 Node 服务器来复制基本示例 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 后,它不起作用,并且在调用server.listen 时,看起来应用程序没有读取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

【问题讨论】:

    标签: javascript node.js kotlin kotlin-js-interop


    【解决方案1】:

    我刚刚找到它,它正在调用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命令顺利运行

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-31
      • 2013-09-05
      • 2011-02-12
      • 2011-08-23
      • 2018-02-05
      相关资源
      最近更新 更多