name:Sophie;shape:fox;condition:new
. It is quite natural to assume that this can be easily converted to a JavaScript object. Therefore, you create an empty object, then an array, dividing the string by the symbol “ ;
". Next - loop through each element of this array, break the lines again, now by the “ :
” symbol. As a result, the first element received from each line becomes the name of the property of the new object, the second one - the value.querystring
. const weirdoString = `name:Sophie;shape:fox;condition:new`; const result = querystring.parse(weirdoString, `;`, `:`); // : // { // name: `Sophie`, // shape: `fox`, // condition: `new`, // };
--inspect
key, it will report the URL. Go to this address in Chrome. And now - a pleasant surprise. We are available to debug Node.js using the Chrome developer tools. Happy times are here. Here is a guide on this topic from Paul Irish.process.nextTick()
function should be called process.sendThisToTheStartOfTheQueue()
. And setImmediate()
- sendThisToTheEndOfTheQueue()
.nextTick
starting from Node v0.10.0. A small retreat. I always thought that in React props
should be called stuffThatShouldStayTheSameIfTheUserRefreshes
, and state
- stuffThatShouldBeForgottenIfTheUserRefreshes
. The fact that these names have the same length, consider a good match. require(`http`) .createServer() .listen({ port: 8080, host: `localhost`, }) .on(`request`, (req, res) => { res.end(`Hello World!`); });
http.Server
about her - not a word. However, it can be found in the description of net.Server
, which is http.Server
.fs
module, can be relative. The starting point is the current working directory returned by process.cwd()
. Probably, this is what everyone knows, but I always thought that I could not do without full ways. const fs = require(`fs`); const path = require(`path`); // ... fs.readFile(path.join(__dirname, `myFile.txt`), (err, data) => { // - }); // ? fs.readFile(`./path/to/myFile.txt`, (err, data) => { // - });
myFilePath = `/someDir/someFile.json`; path.parse(myFilePath).base === `someFile.json`; // true path.parse(myFilePath).name === `someFile`; // true path.parse(myFilePath).ext === `.json`; // true
console.dir(obj, {colors: true})
construct allows objects to be displayed in the console with properties and values ​​highlighted in color. This makes it easier to read logs.setInterval()
to clean the database once a day. By default, the Node event loop will not stop as long as there is code that is scheduled to be executed using setInterval()
. If you want to give Node a rest (I don’t know, in fact, what advantages you can get from this), use the unref()
function. const dailyCleanup = setInterval(() => { cleanup(); }, 1000 * 60 * 60 * 24); dailyCleanup.unref();
process.kill(process.pid, `SIGTERM`);
process.kill(process.pid, os.constants.signals.SIGTERM);
require(`net`).isIP(`10.0.0.1`)
4
. require(`net`).isIP(`cats`)
0
.os.EOL
. On Windows, this will give \r\n
, on all other operating systems - \n
. os.EOL
will ensure uniform code behavior in different operating systems.os.EOL
can lead to trouble. The fact is that here it is necessary to proceed from the assumption that in a certain file either CRLF ( \r\n
) or LF ( \n
) can be used, but one cannot be completely sure of such an assumption.os.EOL
is not a useless toy. For example, this thing may be useful when generating log files that are not planned to be transferred to other operating systems. In this case, os.EOL
ensures that such files are correctly displayed, for example, for viewing which is used Notepad in Windows Server. const fs = require(`fs`); // CRLF fs.readFile(`./myFile.txt`, `utf8`, (err, data) => { data.split(`\r\n`).forEach(line => { // - }); }); // const os = require(`os`); fs.readFile(`./myFile.txt`, `utf8`, (err, data) => { data.split(os.EOL).forEach(line => { // - }); });
http.STATUS_CODES
object. His keys are state codes, and the values ​​are their names. someResponse.code === 301; // true require(`http`).STATUS_CODES[someResponse.code] === `Moved Permanently`; // true
const jsonData = getDataFromSomeApi(); // ! ! const data = JSON.parse(jsonData); // .
process.on(`uncaughtException`, console.error);
try…catch
blocks when I program to order, but in home projects ...on()
method, EventEmitter
objects EventEmitter
have a once()
method. I am quite sure that I am the last person on Earth who has learned about it. Therefore, I limit myself to a simple example, which everyone will understand. server.once(`request`, (req, res) => res.end(`No more from me.`));
new console.Console(standardOut, errorOut)
dns.lookup()
, and cache the results. Or, use the dnscache package, which does the same. dns.lookup(`www.myApi.com`, 4, (err, address) => { cacheThisForLater(address); });
fs
. The developers have done a lot of work aimed at unifying the interaction of Node with various operating systems, but their capabilities are not unlimited. As a result, features of various operating systems break the ocean surface of the code as sharp reefs, which are also mined. And you in this drama play the role of a boat that can sit on one of the reefs.fs
are not reducible to the usual: “Windows and everyone else”, so we cannot just brush it off, hiding behind the idea: “yes, who uses Windows”. (I first wrote here a whole speech about anti-Windows sentiment in web development, but in the end I decided to remove it, otherwise I got my eyes on my forehead from this my sermon).fs
module. I am sure that these revelations can bite somebody as well as a roasted rooster.mode
property of the object returned by fs.stats(),
different in Windows and other operating systems. On Windows, it may not correspond to file access constants, such as fs.constants.S_IRWXU
.fs.lchmod()
function is available only in macOS.fs.symlink()
with the type
parameter is supported only on Windows.recursive
option, which can be passed to the fs.watch()
function, works only on Windows and macOS.fs.watch()
callback function accepts a file name only on Linux and Windows.fs.open()
call with the a+
flag for the directory will work on FreeBSD and on Windows, but will not work on macOS and Linux.position
parameter passed to fs.write()
will be ignored in Linux if the file is opened in attachment mode. The kernel ignores the position and appends data to the end of the file.net
module is a thing. It is the basis of the http
module. It made me think that if you need to organize the interaction of servers (as it turned out, I needed it), should I use the net
module only?net
and http
, and compare them, I set up a couple of servers (I hope you are listening to Japanese rap) and loaded them with requests. As a result, http.Server
was able to process approximately 3400 requests per second, and net.Server
- approximately 5500. In addition, net.Server
easier to net.Server
. // . – TCP-, – HTTP ( server.js). // . // . 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);
// . – TCP, – HTTP. // JSON, , . 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)); }); });
node
in the terminal and pressed Enter , you can enter a command like .load someFile.js
and the system will load the requested file (for example, a bunch of constants can be specified in such a file).NODE_REPL_HISTORY=""
in order to disable the recording of history to a file. In addition, I learned (at least - remembered) that the REPL history file, which allows you to travel to the past, is stored at ~/.node_repl_history
._»
is the name of a variable that stores the result of the last expression executed. I think it can be useful.os.arch()
on the command line to find out the architecture of the OS. A construct like require(`os`).arch();
need not.Source: https://habr.com/ru/post/318322/
All Articles