What is the difference between a Sync and Async method in Node.JS?

Asked

Viewed 28 times

0

I am developing a file upload application on Node.JS. There is a snippet in the code that transfers the file to a specific folder on the server...

router.post('/', (req, res, next) => {
    const formidable = require('formidable');
    const fs = require('fs');
    const form = new formidable.IncomingForm();

    form.parse(req, (err, fields, files) => {

    const path = require('path');
    const oldpath = files.filetoupload.path;
    const newpath = path.join(__dirname, '..', files.filetoupload.name);

    fs.renameSync(oldpath, newpath);
    res.send('File uploaded and moved!');
  });
});

What is the difference between using Fs.renameSync() and Fs.Rename()? Performing Google search I saw that I can use the Fs.copyFile() function that has the same result. So... I’m in doubt as to how best to use?

Follow the upload part code:

var express = require('express');
var router = express.Router();

router.get('/', function (req, res, next) {
    res.render('index', { title: 'Express' });
});

router.post('/', (req, res, next) => {
    const formidable = require('formidable');
    const fs = require('fs');
    const form = new formidable.IncomingForm()

    form.parse(req, (err, fields, files) => {
        const path = require('path');
        const oldpath = files.filetoupload.path;
        const newpath = path.join(__dirname, '..', files.filetoupload.name);
        fs.copyFile(oldpath, newpath, (err) => {
             if (err) return console.log(err);
             res.send('File Uploaded and Moved!')
     });
  });
});

module.exports = router;

1 answer

0


the asynchronous function does not wait task finish to start the next one which makes the code faster synchronous function is simpler to do but the code always waits for one task to finish to do another and this slows the response speed in small programs is quiet but when the number of requests at the same time increases the potential difference is large

      console.time("Assincrono");
       var counter = 0;

      for(var i = 0; i<1000; i++){
        fs.readFile("meu_arquivo.txt", (err, data)=>{
          if(err){
            return console.error(err);
          }
          counter++;
          console.log("Assincrono" + data.toString());
          if(counter === 1000){
              console.timeEnd("Assincrono");
          }
          });
           }

execution speed /700 ms asynchronous

 console.time("sincrono");
 var counter = 0;

 for(var i = 0; i<1000; i++){
  var data = fs.readFileSync("meu_arquivo.txt");
  console.log("sincrono" + data.toString());
 }
 console.timeEnd("sincrono");

execution speed //900 ms synchronous

Browser other questions tagged

You are not signed in. Login or sign up in order to post.