来自 前端知识 2019-11-08 09:12 的文章
当前位置: 金沙澳门官网网址 > 前端知识 > 正文

创办贰个服务器能依靠不一样的url地址央浼例外

net 模块大约比http快上两倍

小编在文书档案中看见有个别有关两岸质量的批评,还非常运营了五个服务器来张开实际比较。结果来看http.Server大概每秒能够连接3400个央浼,而net.Server能够接入大约5500个央求。

JavaScript

// This makes two connections, one to a tcp server, one to an http server (both in server.js) // It fires off a bunch of connections and times the response // Both send strings. const net = require(`net`); const http = require(`http`); function parseIncomingMessage(res) { return new Promise((resolve) => { let data = ``; res.on(`data`, (chunk) => { data += chunk; }); res.on(`end`, () => resolve(data)); }); } const testLimit = 5000; /* ------------------ */ /* -- NET client -- */ /* ------------------ */ function testNetClient() { const netTest = { startTime: process.hrtime(), responseCount: 0, testCount: 0, payloadData: { type: `millipede`, feet: 100, test: 0, }, }; function handleSocketConnect() { netTest.payloadData.test++; netTest.payloadData.feet++; const payload = JSON.stringify(netTest.payloadData); this.end(payload, `utf8`); } function handleSocketData() { netTest.responseCount++; if (netTest.responseCount === testLimit) { const hrDiff = process.hrtime(netTest.startTime); const elapsedTime = hrDiff[0] * 1e3 + hrDiff[1] / 1e6; const requestsPerSecond = (testLimit / (elapsedTime / 1000)).toLocaleString(); console.info(`net.Server handled an average of ${requestsPerSecond} requests per second.`); } } while (netTest.testCount < testLimit) { netTest.testCount++; const socket = net.connect(8888, handleSocketConnect); socket.on(`data`, handleSocketData); } } /* ------------------- */ /* -- HTTP client -- */ /* ------------------- */ function testHttpClient() { const httpTest = { startTime: process.hrtime(), responseCount: 0, testCount: 0, }; const payloadData = { type: `centipede`, feet: 100, test: 0, }; const options = { hostname: `localhost`, port: 8080, method: `POST`, headers: { 'Content-Type': `application/x-www-form-urlencoded`, }, }; function handleResponse(res) { parseIncomingMessage(res).then(() => { httpTest.responseCount++; if (httpTest.responseCount === testLimit) { const hrDiff = process.hrtime(httpTest.startTime); const elapsedTime = hrDiff[0] * 1e3 + hrDiff[1] / 1e6; const requestsPerSecond = (testLimit / (elapsedTime / 1000)).toLocaleString(); console.info(`http.Server handled an average of ${requestsPerSecond} requests per second.`); } }); } while (httpTest.testCount < testLimit) { httpTest.testCount++; payloadData.test = httpTest.testCount; payloadData.feet++; const payload = JSON.stringify(payloadData); options[`Content-Length`] = Buffer.byteLength(payload); const req = http.request(options, handleResponse); req.end(payload); } } /* -- Start tests -- */ // flip these occasionally to ensure there's no bias based on order setTimeout(() => { console.info(`Starting testNetClient()`); testNetClient(); }, 50); setTimeout(() => { console.info(`Starting testHttpClient()`); testHttpClient(); }, 2000);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
// This makes two connections, one to a tcp server, one to an http server (both in server.js)
// It fires off a bunch of connections and times the response
 
// Both send strings.
 
const net = require(`net`);
const http = require(`http`);
 
function parseIncomingMessage(res) {
  return new Promise((resolve) => {
    let data = ``;
 
    res.on(`data`, (chunk) => {
      data += chunk;
    });
 
    res.on(`end`, () => resolve(data));
  });
}
 
const testLimit = 5000;
 
 
/*  ------------------  */
/*  --  NET client  --  */
/*  ------------------  */
function testNetClient() {
  const netTest = {
    startTime: process.hrtime(),
    responseCount: 0,
    testCount: 0,
    payloadData: {
      type: `millipede`,
      feet: 100,
      test: 0,
    },
  };
 
  function handleSocketConnect() {
    netTest.payloadData.test++;
    netTest.payloadData.feet++;
 
    const payload = JSON.stringify(netTest.payloadData);
 
    this.end(payload, `utf8`);
  }
 
  function handleSocketData() {
    netTest.responseCount++;
 
    if (netTest.responseCount === testLimit) {
      const hrDiff = process.hrtime(netTest.startTime);
      const elapsedTime = hrDiff[0] * 1e3 + hrDiff[1] / 1e6;
      const requestsPerSecond = (testLimit / (elapsedTime / 1000)).toLocaleString();
 
      console.info(`net.Server handled an average of ${requestsPerSecond} requests per second.`);
    }
  }
 
  while (netTest.testCount < testLimit) {
    netTest.testCount++;
    const socket = net.connect(8888, handleSocketConnect);
    socket.on(`data`, handleSocketData);
  }
}
 
 
/*  -------------------  */
/*  --  HTTP client  --  */
/*  -------------------  */
function testHttpClient() {
  const httpTest = {
    startTime: process.hrtime(),
    responseCount: 0,
    testCount: 0,
  };
 
  const payloadData = {
    type: `centipede`,
    feet: 100,
    test: 0,
  };
 
  const options = {
    hostname: `localhost`,
    port: 8080,
    method: `POST`,
    headers: {
      'Content-Type': `application/x-www-form-urlencoded`,
    },
  };
 
  function handleResponse(res) {
    parseIncomingMessage(res).then(() => {
      httpTest.responseCount++;
 
      if (httpTest.responseCount === testLimit) {
        const hrDiff = process.hrtime(httpTest.startTime);
        const elapsedTime = hrDiff[0] * 1e3 + hrDiff[1] / 1e6;
        const requestsPerSecond = (testLimit / (elapsedTime / 1000)).toLocaleString();
 
        console.info(`http.Server handled an average of ${requestsPerSecond} requests per second.`);
      }
    });
  }
 
  while (httpTest.testCount < testLimit) {
    httpTest.testCount++;
    payloadData.test = httpTest.testCount;
    payloadData.feet++;
 
    const payload = JSON.stringify(payloadData);
 
    options[`Content-Length`] = Buffer.byteLength(payload);
 
    const req = http.request(options, handleResponse);
    req.end(payload);
  }
}
 
/*  --  Start tests  --  */
// flip these occasionally to ensure there's no bias based on order
setTimeout(() => {
  console.info(`Starting testNetClient()`);
  testNetClient();
}, 50);
 
setTimeout(() => {
  console.info(`Starting testHttpClient()`);
  testHttpClient();
}, 2000);

JavaScript

// This sets up two servers. A TCP and an HTTP one. // For each response, it parses the received string as JSON, converts that object and returns a string const net = require(`net`); const http = require(`http`); function renderAnimalString(jsonString) { const data = JSON.parse(jsonString); return `${data.test}: your are a ${data.type} and you have ${data.feet} feet.`; } /* ------------------ */ /* -- NET server -- */ /* ------------------ */ net .createServer((socket) => { socket.on(`data`, (jsonString) => { socket.end(renderAnimalString(jsonString)); }); }) .listen(8888); /* ------------------- */ /* -- HTTP server -- */ /* ------------------- */ function parseIncomingMessage(res) { return new Promise((resolve) => { let data = ``; res.on(`data`, (chunk) => { data += chunk; }); res.on(`end`, () => resolve(data)); }); } http .createServer() .listen(8080) .on(`request`, (req, res) => { parseIncomingMessage(req).then((jsonString) => { res.end(renderAnimalString(jsonString)); }); });

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// This sets up two servers. A TCP and an HTTP one.
// For each response, it parses the received string as JSON, converts that object and returns a string
const net = require(`net`);
const http = require(`http`);
 
function renderAnimalString(jsonString) {
  const data = JSON.parse(jsonString);
  return `${data.test}: your are a ${data.type} and you have ${data.feet} feet.`;
}
 
 
/*  ------------------  */
/*  --  NET server  --  */
/*  ------------------  */
 
net
  .createServer((socket) => {
    socket.on(`data`, (jsonString) => {
      socket.end(renderAnimalString(jsonString));
    });
  })
  .listen(8888);
 
 
/*  -------------------  */
/*  --  HTTP server  --  */
/*  -------------------  */
 
function parseIncomingMessage(res) {
  return new Promise((resolve) => {
    let data = ``;
 
    res.on(`data`, (chunk) => {
      data += chunk;
    });
 
    res.on(`end`, () => resolve(data));
  });
}
 
http
  .createServer()
  .listen(8080)
  .on(`request`, (req, res) => {
    parseIncomingMessage(req).then((jsonString) => {
      res.end(renderAnimalString(jsonString));
    });
  });

var server = http.createServer(funSer).listen(port,ip,fun);

fs 在不相同OS上有一定差异

  • fs.stats()归来的目的中的mode品质在Windows与其余操作系统中存在差异。
  • fs.lchmod()仅在macOS中有效。
  • 仅在Windows中帮助调用fs.symlink()时使用type参数。
  • 仅仅在macOS与Windows中调用fs.watch()时传入recursive选项。
  • 在Linux与Windows中fs.watch()的回调能够流传有个别文件名
  • 使用fs.open()以及a+属性展开有个别目录时独自在FreeBSD以致Windows上起效能,在macOS以致Linux上则设十分。
  • 在Linux下以追加方式打开某些文件时,传入到fs.write()position参数会被忽视。

}else{

Path Parsing:路线深入分析

事先自个儿直接不了然的某部意义正是从某些文件名中深入分析出路线,文件名,文件扩大等等:

JavaScript

myFilePath = `/someDir/someFile.json`; path.parse(myFilePath).base === `someFile.json`; // true path.parse(myFilePath).name === `someFile`; // true path.parse(myFilePath).ext === `.json`; // true

1
2
3
4
myFilePath = `/someDir/someFile.json`;
path.parse(myFilePath).base === `someFile.json`; // true
path.parse(myFilePath).name === `someFile`; // true
path.parse(myFilePath).ext === `.json`; // true

fs.readFile('./index.html',function( error, content){

HTTP 状态码

NodeJS帮大家松开了HTTP状态码及其描述,也正是http.STATUS_CODES,键为状态值,值为描述:
澳门金莎娱乐手机版 1

你可以遵照如下方法运用:

JavaScript

someResponse.code === 301; // true require(`http`).STATUS_CODES[someResponse.code] === `Moved Permanently`; // true

1
2
someResponse.code === 301; // true
require(`http`).STATUS_CODES[someResponse.code] === `Moved Permanently`; // true

var parth = url.parse(req.url).pathname;

自己在翻阅 NodeJS 文书档案中读出的二十个套路

2016/11/21 · JavaScript · NodeJS

原稿出处: David Gilbertson   译文出处:王下邀月熊_Chevalier   

就算如此自身曾经用了三年多的NodeJS,也早就感觉自个儿对其无所不通。但是自个儿周边未有有安静的坐下来留心地翻阅NodeJS的全部文书档案。要是有了解本人的心上人应该明了,小编事先早就看了HTML,DOM,Web APIs,CSS,SVG以致ECMAScript的文书档案,NodeJS是自家这么些种类的结尾三个待翻阅的山峰。在阅读文书档案的历程中小编也发掘了众多自然不精通的学问,作者以为本身有需求分享给我们。可是文书档案越来越多的是兴致索然,因而笔者也以涉猎的次第列举出自己认为须要通晓的点。

fs.readFile('./default.html',function( error, content){

os.EOF

不明了您有未有手写过行截止符,看上去可不美丽啊。NodeJS内置了os.EOF,其在Windows下是rn,其余地点是n,使用os.EOL可见让您的代码在差异的操作系统上保险风流洒脱致性:

JavaScript

const fs = require(`fs`); // bad fs.readFile(`./myFile.txt`, `utf8`, (err, data) => { data.split(`rn`).forEach(line => { // do something }); }); // good const os = require(`os`); fs.readFile(`./myFile.txt`, `utf8`, (err, data) => { data.split(os.EOL).forEach(line => { // do something }); });

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const fs = require(`fs`);
// bad
fs.readFile(`./myFile.txt`, `utf8`, (err, data) => {
  data.split(`rn`).forEach(line => {
    // do something
  });
});
// good
const os = require(`os`);
fs.readFile(`./myFile.txt`, `utf8`, (err, data) => {
  data.split(os.EOL).forEach(line => {
    // do something
  });
});

var url = urls.parse(req.url);

周旋地址

你传入fs模块的相距可以是对峙地址,即相对于process.cwd()。估摸某人曾经知道了,不过笔者事先一直认为是只可以采纳相对化地址:

JavaScript

const fs = require(`fs`); const path = require(`path`); // why have I always done this... fs.readFile(path.join(__dirname, `myFile.txt`), (err, data) => { // do something }); // when I could just do this? fs.readFile(`./path/to/myFile.txt`, (err, data) => { // do something });

1
2
3
4
5
6
7
8
9
10
const fs = require(`fs`);
const path = require(`path`);
// why have I always done this...
fs.readFile(path.join(__dirname, `myFile.txt`), (err, data) => {
  // do something
});
// when I could just do this?
fs.readFile(`./path/to/myFile.txt`, (err, data) => {
  // do something
});

res.writeHead(400,{'Content-Type':'text/plain;charset="utf-8"'});

REPL tricks

  • 假设您是在REPL方式下,就是直接输入node然后跻身彼此状态的格局。你能够直接输入.load someFile.js然后能够载入蕴涵自定义常量的公文。
  • 能够透过设置NODE_REPL_HISTORY=""来幸免将日志写入到文件中。
  • _用来记录最后贰个总结值。
  • 在REPL运转之后,全体的模块都已直接加载成功。能够应用os.arch()而不是require(os).arch()来使用。

    1 赞 3 收藏 评论

澳门金莎娱乐手机版 2

}else{

Server.listen 能够行使Object作为参数

我更爱好命名参数的主意调用函数,那样相较于仅依照顺序的无命名参数法会更加直观。别忘了Server.listen也得以动用有些Object作为参数:

JavaScript

require(`http`) .createServer() .listen({ port: 8080, host: `localhost`, }) .on(`request`, (req, res) => { res.end(`Hello World!`); });

1
2
3
4
5
6
7
8
9
require(`http`)
  .createServer()
  .listen({
    port: 8080,
    host: `localhost`,
  })
  .on(`request`, (req, res) => {
    res.end(`Hello World!`);
  });

只是那个特点不是表明在http.Server本条API中,而是在其父级net.Server的文书档案中。

res.end();

Just this once()

除了on方法,once措施也适用于具备的伊夫ntEmitters,希望本人不是最后才掌握这几个的:

JavaScript

server.once(`request`, (req, res) => res.end(`No more from me.`));

1
server.once(`request`, (req, res) => res.end(`No more from me.`));

});

Use Signal Constants

倘使你品味在NodeJS中杀死有些进程,估量您用过如下语法:

JavaScript

process.kill(process.pid, `SIGTERM`);

1
process.kill(process.pid, `SIGTERM`);

其生机勃勃没啥难题,可是既然第一个参数相同的时候能够选择字符串与整形变量,那么还比不上利用全局变量呢:

JavaScript

process.kill(process.pid, os.constants.signals.SIGTERM);

1
process.kill(process.pid, os.constants.signals.SIGTERM);

res.write(error.message);

nextTick 与 setImmediate的区别

这两货的分别可能光从名字上还看不出来,作者认为应该给它们取个外号:

  • process.nextTick()应该为process.sendThisToTheStartOfTheQueue()
  • setImmediate应该为sendThisToTheEndOfTheQueue()

再说句不相干的,React中的Props应为stuffThatShouldStayTheSameIfTheUserRefreshes,而State应该为stuffThatShouldBeForgottenIfTheUserRefreshes

//引进的创设立模型块  http、url、fs

DNS lookup

有些年轻人告诉本人,Node并不会缓存DNS查询消息,由此你在接受URAV4L之后要等个几纳秒才具取获得数码。但是事实上您可以应用dns.lookup()澳门金莎娱乐手机版 ,来缓存数据:

JavaScript

dns.lookup(`www.myApi.com`, 4, (err, address) => { cacheThisForLater(address); });

1
2
3
dns.lookup(`www.myApi.com`, 4, (err, address) => {
  cacheThisForLater(address);
});

server.listen(port , ip);

Logging with colors

别忘了console.dir(obj,{colors:true})可见以差别的情调打字与印刷出键与值,这点会大大增添日志的可读性。

break;

防止非凡崩溃

突发性碰到如下这种引致服务端崩溃的景观也许挺无助的:

JavaScript

const jsonData = getDataFromSomeApi(); // But oh no, bad data! const data = JSON.parse(jsonData); // Loud crashing noise.

1
2
const jsonData = getDataFromSomeApi(); // But oh no, bad data!
const data = JSON.parse(jsonData); // Loud crashing noise.

本身为着幸免这种景况,在大局加上了一个:

JavaScript

process.on(`uncaughtException`, console.error);

1
process.on(`uncaughtException`, console.error);

自然,这种方法绝不是至上试行,要是是在大型项目中本人只怕会动用PM2,然后将具有恐怕崩溃的代码参预到try...catch中。

res.end();

V8 Inspector

--inspect参数运维你的Node应用程序,它会报告你某些ULacrosseL。将该UQX56L复制到Chrome中并展开,你就能够运用Chrome DevTools来调解你的Node应用程序啦。详细的实验能够参照那篇小说。可是必要小心的是,该参数依旧归于实验性质。
澳门金莎娱乐手机版 3

* url是url路由模块

动用setInterval执行准期职责

本人燃膏继晷使用setInterval来定时实施数据库清理职务,然则暗中同意情状下在设有setInterval的时候NodeJS并不会脱离,你能够行使如下的主意让Node沉睡:

JavaScript

const dailyCleanup = setInterval(() => { cleanup(); }, 1000 * 60 * 60 * 24); dailyCleanup.unref();

1
2
3
4
const dailyCleanup = setInterval(() => {
  cleanup();
}, 1000 * 60 * 60 * 24);
dailyCleanup.unref();

//定义端口号

Custom Console

您能够运用new console.Console(standardOut,errorOut),然后设置自定义的输出流。你能够采纳创造console将数据输出到文件恐怕Socket可能第三方中。

res.write(content);

querystring:能够充作通用分析器的模块

无数时候我们会从数据库或任何地方得到这种诡异格式的字符串:name:Sophie;shape:fox;condition:new,平时的话我们会使用字符串切割的法子来说字符串划分到JavaScript Object。然而querystring也是个不错的现有的工具:

JavaScript

const weirdoString = `name:Sophie;shape:fox;condition:new`; const result = querystring.parse(weirdoString, `;`, `:`); // result: // { // name: `Sophie`, // shape: `fox`, // condition: `new`, // };

1
2
3
4
5
6
7
8
const weirdoString = `name:Sophie;shape:fox;condition:new`;
const result = querystring.parse(weirdoString, `;`, `:`);
// result:
// {
//   name: `Sophie`,
//   shape: `fox`,
//   condition: `new`,
// };

var server = new http.Server();

IP Address Validation

NodeJS中包蕴内置的IP地址校验工具,那或多或少方可免受你写额外的正则表明式:

JavaScript

require(`net`).isIP(`10.0.0.1`) 返回 4 require(`net`).isIP(`cats`) 返回 0

1
2
require(`net`).isIP(`10.0.0.1`) 返回 4
require(`net`).isIP(`cats`) 返回 0

//引进的组装模块  http、url、fs

const url = require('url');

break;

break;

const port = 2000;

res.end();

//监听三个端口

});

//读取文件内容

res.writeHead(200,{'Content-Type':'text/html;charset="utf-8"'});

var fun = function(){

}

default:

res.writeHead(400,{'Content-Type':'text/plain;charset="utf-8"'});

const http = require('http');

2.创建nodejs服务器;

const url = require('url');

case '/list':

const ip = '192.168.1.118';//主机IP

});

var funSer = function(req,res){

if(error){//若是有不那个时候,展现错误消息

var fun = function(){

res.end();

const ip = '192.168.1.118';//主机IP

//定义主机IP常量名称

console.log('server start');

3.得到U本田CR-VL部分块的内容 url;

fs.readFile('./show.html',function( error, content){

const url = require('url');

});

console.log('server start');

});

res.writeHead(200,{'Content-Type':'text/html;charset="utf-8"'});//头信息

const ip = '192.168.0.102';

const url = require('url');

res.end();

var parth = url.parse(req.url).pathname;

const fs = require('fs');

var server = http.createServer(funSer).listen(port,ip,fun);

var funSer = function(req,res){

case '' || '/':

//获取乞求的url地址

case '/show':

if(error){

var server = http.createServer(function(req,res){

}

break;

if(error){

//获取url地址块的原委  如:/path/show

const fs = require('fs');

//引进的组装模块  http、url、fs

//console.log(url.pathname);

本文由金沙澳门官网网址发布于前端知识,转载请注明出处:创办贰个服务器能依靠不一样的url地址央浼例外

关键词: