当前位置:   article > 正文

Node.js 用TS写一个简单的静态服务器_node后台服务可以用ts写吗

node后台服务可以用ts写吗

首先要在node使用ts,要做下面几件事:

因为ts是建立在js的基础之上的,但是node不能直接运行ts代码,所以需要使用工具将ts代码编译成js代码。

 yarn global add ts-node-dev

 @types/node  是ts中类型声明文件,可以让我们享受类型系统的好处,这样idea就不会报错并且能自动引用。

yarn add --dev @types/node

做完上面的工作之后,其它流程就和js一样,yarn add 其它依赖就好。

  1. import * as http from 'http';
  2. import {IncomingMessage, ServerResponse} from 'http';
  3. import * as fs from 'fs';
  4. import * as p from 'path'; // 正确处理系统文件路径
  5. import * as url from 'url'; // 处理url字符转相关api
  6. const server = http.createServer();
  7. const publicDir = p.resolve(__dirname, 'public'); // 当前文件路径
  8. let cacheAge = 365 * 86400 // 可控制缓存时间
  9. server.on('request', (request: IncomingMessage, response: ServerResponse)=> {
  10. const {method, url: path, headers} = request; // url重命名为path字段
  11. const {pathname, search} = url.parse(path); // pathname获取url路径的部分 search获取url序列化查询部分
  12. if (method === 'POST') {
  13. response.statusCode = 405
  14. response.end()
  15. return
  16. }
  17. let filename = pathname.substr(1);
  18. if (filename === '') {
  19. filename = 'index.html'
  20. }
  21. fs.readFile(p.resolve(publicDir, filename), (err, data) => {
  22. if (err) {
  23. console.log(err,'err');
  24. if (err.errno === -2) {
  25. response.statusCode = 404;
  26. fs.readFile(p.resolve(publicDir, '404.html'), (err1, data1) => {
  27. response.end(data1);
  28. })
  29. } else {
  30. response.statusCode = 500;
  31. response.setHeader('content-type', 'text/html; charset=utf-8')
  32. response.end('服务器繁忙,请稍后再试');
  33. }
  34. } else {
  35. response.setHeader(`Cache-Control`, `public, max-age=${cacheAge}`)
  36. response.end(data)
  37. }
  38. })
  39. })
  40. server.listen(8888) // 端口名

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/煮酒与君饮/article/detail/797209
推荐阅读
相关标签
  

闽ICP备14008679号