Basic of Node.js “Synchronization processing and Non Synchronization processing”

この記事は約4分で読めます。

To understand the terms related to Node.js, I would like to discuss about Synchronization processing and Non Synchronization processing.

Synchronization processing and Non Synchronization processing

In Node.js the processes of file, network or input/output of database will be done by non synchronization processing to prioritize maximizing  its performance.

Many libraries provides both non synchronization processing functions also synchronization processing functions as well.

Non Synchronization processingSynchronization processingMeaning
fs.readFile()fs.readFileSync()Read file
fs.writeFile()fs.writeFileSync()Write file
fs.readdir()fs.readdirSync()Retrieve list of folders and files
zlib.gzip()zlib.gzipSync()Compress
crypto.pbkbf2()crypto.pbkbf2Sync()Encrypt password

Actual example of Synchronization and Non Synchronization processing

const fs = require('fs')

//Load file in Synchronization  -- A
const data = fs.readFileSync('test.txt', 'utf-8')
console.log(data)

//Load file in Non Synchronization  --B
fs.readFile('test.txt', 'utf-8', readHandler)
  // Once the loading has been done
  function readHandler (err, data) {
    console.log(data) 
  }

The result

The results are the same with A and B. But Non Synchronization(B) needs additionally include the function that will be called after file loading.

C:\Users\Owner\Desktop\node>node sync-readfile.js
This is the test. It is in "test.txt"  // Result from A
This is the test. It is in "test.txt" // Result from B

What is nameless function?

When we use nameless function we can easily define another new function. And the nameless function can be specified into function parameters as function objects.

// Example: transfer small caps to all caps

const s = 'Actions speak louder than words.'
const r = s.replace(/[a-z]+/g, function (m) {
  returnm.toUpperCase()
})
console.log(r)

// Example: Sort numbers in an array
const ar = [100, 1, 30, 53, 20, 11, 4]
ar.sort((a, b) => {return b -a})
console.log(ar)

The result

Like this example nameless function allows to define another function and the new function can be used as argument of functions or function objects.

C:\Users\Owner\Desktop\node>node mumei2.js
ACTIONS SPEAK LOUDER THAN WORDS.
[ 100, 53, 30, 20, 11, 4, 1 ]
タイトルとURLをコピーしました