使用vscode + typescript + nodejs 写一个简单本地服务器

目录结构:

根目录
│  package.json
│  tsconfig.json
│  yarn.lock
│
├─.vscode
│      launch.json
│
├─dist
│      client.js
│      client.js.map
│      server.js
│      server.js.map
│
└─src
        client.ts
        server.ts

launch.json 文件:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Debug IM",
            "args": ["${workspaceFolder}/src/server.ts"],
            "runtimeArgs": ["--nolazy","-r","ts-node/register"],
            "sourceMaps": true,
            "cwd": "${workspaceRoot}",
            "protocol": "inspector",
            "console": "integratedTerminal",
            "env": {
                "NODE_ENV":"ts-node"
            },
            "serverReadyAction":{
                "pattern": "listening on port ([0-9]+)",
                "uriFormat": "http://localhost:%s",
                "action": "openExternally"
            }
        }
    ]
}

package.json 文件:

{
  "name": "im",
  "version": "1.0.0",
  "description": "chat",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node dist/index.js",
    "dev": "set NODE_ENV=ts-node&&ts-node -r tsconfig-paths/register src/server.ts",
    "dev:debug": "set NODE_ENV=ts-node&&node --inspect-brk --nolazy -r tsconfig-paths/register -r ts-node/register src/server.ts",
    "build":"tsc -p tsconfig.json"
  },
  "author": "max",
  "license": "MIT",
  "dependencies": {
    "@types/node": "^12.7.2",
    "ts-node": "^8.3.0",
    "typescript": "^3.5.3"
  }
}


tsconfig.json 文件:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es6",
        "outDir": "./dist",
        "baseUrl": "./",
        "sourceMap": true,
        "noImplicitAny": true
    },
    "include": [
        "src/*"
    ],
    "exclude": ["node_modules"]
}

server.ts 文件:

import * as net from 'net'

let server = net.createServer();
server.on('connection',(socket:net.Socket) => {
    socket.write('Hello')
    socket.end()
})

server.listen(80)
console.log('listening on port 80!')

client.ts 文件:

import * as net from 'net'

let client = net.connect({port:80})
client.on('data',(data) => {
    console.log(data.toString())
})

在终端中使用 npm run build,编译 client.ts、server.ts , 编译出的文件在 dist 目录

确认本机相应端口没有被占用
启动服务端(2选1):
1、直接在vscode中按F5(launch.json 文件已做相应配置)
2、终端命令启动:node .\dist\server.js

启动客户端:
1、终端命令启动:node .\dist\client.js

客户端执行效果图

你可能感兴趣的:(使用vscode + typescript + nodejs 写一个简单本地服务器)