Node.js Express Script to Convert Sass (SCSS) to CSS Online App Using Node-Sass Library Full Project For Beginners

Node.js Express Script to Convert Sass (SCSS) to CSS Online App Using Node-Sass Library Full Project For Beginners

 

 

 

Welcome folks today in this folks we will be making online app of converting scss to css online tool using node-sass library. All the source code of the application is given below.

 

 

Live Demo

 

 

You can check out the live demo of this tool here

 

 

 

Screenshot

 

 

 

 

 

 

 

 

Get Started

 

 

 

In order to get started we need to install the node-sass library globally inside our system.

We will execute the following commands

 

npm init -y

 

This will create a package.json file inside your root directory

 

And now we need to install node-sass inside node.js project

 

npm i -g node-sass

 

This will work only for windows

 

In order to install on linux or ubuntu

 

we need to execute the below command

 

sudo npm install -g --unsafe-perm node-sass

 

 

 

Converting SCSS to CSS

 

 

 

Now using this library we will be converting scss to css library. We need to execute the following command

 

node-sass input.scss output.css

 

here we are taking the input sass file input.scss and converting to output css file output.css

 

 

 

Source Code

 

 

Now just install the following dependencies

 

npm i express

 

npm i nodemon

 

npm i ejs

 

npm i multer

 

After installing all these dependencies make a index.js file and copy paste the following code

 

 

index.js

 

 

 

const express = require('express')

const fs = require('fs')

const { exec } = require('child_process')


const path = require('path')

const multer = require('multer')

const bodyparser = require('body-parser')

const PORT= 4000

const app = express()

app.use(bodyparser.urlencoded({extended:false}))

app.use(bodyparser.json())

app.set("view engine","ejs")

var dir = 'public';
var subDirectory = 'public/uploads'

if (!fs.existsSync(dir)){
    fs.mkdirSync(dir);

    fs.mkdirSync(subDirectory)

}

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, 'public/uploads')
    },
    filename: function (req, file, cb) {
      cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
    }
})


const scssFileFilter = function (req, file, callback) {
  var ext = path.extname(file.originalname);
  if (
    ext !== ".scss"
  ) {
    return callback("This Extension is not supported");
  }
  callback(null, true);
};

var scsstocssupload = multer({
  storage: storage,
  fileFilter: scssFileFilter,
}).single("file");

app.post('/uploadscsstocss',(req,res) => {
  scsstocssupload(req, res, function (err) {
    if (err) {
      return res.end("Error uploading file.");
    }
    res.json({
      path: req.file.path,
    });
  });
})

app.post('/scsstocss',(req,res) => {

  console.log(req.body.path);

  outputFilePath = Date.now() + "output.css";

  exec(
    `node-sass ${req.body.path} ${outputFilePath}`,
    (err, stdout, stderr) => {
      if (err) {
        res.json({
          error: "some error takes place",
        });
      }
      res.json({
        path: outputFilePath,
      });
    }
  );
  
})

app.get('/scsstocss',(req,res) => {
  res.render('scsstocss',{title:'FREE SCSS (SASS) to CSS Online Converter Tool - Best SASS to CSS Converter - FreeMediaTools.com'})
})

app.get("/download", (req, res) => {
  var pathoutput = req.query.path;
  console.log(pathoutput);
  var fullpath = path.join(__dirname, pathoutput);
  res.download(fullpath, (err) => {
    if (err) {
      fs.unlinkSync(fullpath);
      res.send(err);
    }
    fs.unlinkSync(fullpath);
  });
});

app.listen(PORT, () => {
  console.log(`App is listening on Port ${PORT}`);
});

 

See also  Google Photos API Tutorial to Upload Multiple Photos From Local Storage & HTML5 Form in Browser Using Axios & Javascript Full Project For Beginners

 

Now make a views folder inside the root directory and inside it create a scsstocss.ejs file and copy paste the following code

 

 

views/scsstocss.ejs

 

 

 

<!DOCTYPE html>
<html>
  <head>
    <title><%=title%></title>
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
    />
  </head>
  <body>
      <div class="container">
          <h1 class="text-center">
              SASS(SCSS) to CSS Converter
          </h1>
          <br><br>
          <form id="form">
              <div class="form-group">
                  <label for="pdf">Upload SASS File:</label>
                  <input class="form-control" type="file" name="" id="upload-input" required accept=".scss">
              </div>
              <div id="progress" class="progress">
                <div id="progress-bar" class="progress-bar" role="progressbar"></div>
              </div>
              <div class="form-group">
                  <button class="btn btn-block btn-danger">
                      Download CSS File
                  </button>
              </div>
          </form>
          <br></br>
      </div>
</body>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script>
    var files
      $('#form').on('submit', function (e){
        e.preventDefault()
    //$('#upload-input').click();
    $("#button").text("Uploading File")
    $("#button").prop("disabled","true")
    $('.progress-bar').text('0%');
    $('.progress-bar').width('0%');
    convertFile()
});
$('#upload-input').on('change', function(){
  files = $(this).get(0).files;
  var fileExtension = ['scss'];
        if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
           $(this).val("") 
    
swal ( "Oops" ,"Please Upload a SCSS File",  "error" )

        }
})

function convertFile(){
  if (files.length > 0){
    // create a FormData object which will be sent as the data payload in the
    // AJAX request
    var formData = new FormData();
    // loop through all the selected files and add them to the formData object
    for (var i = 0; i < files.length; i++) {
      var file = files[i];
      // add the files to formData object for the data payload
      formData.append('file', file, file.name);
    }
    console.log(formData)
    var formdata2 = new FormData()
    $.ajax({
      url: '/uploadscsstocss',
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      success: function(data){
          var data2 = {path:data.path}
          console.log('upload successful!\n' + data.path);
          $("#button").text("File Uploaded Now Processing")
          $("#button").prop("disabled",true);
          formdata2.append('path',data.path)
          $.ajax({
              url:'/scsstocss',
              type:'POST',
              data:JSON.stringify(data2),
              contentType: "application/json",
              dataType:"json",
      success:function(data){

        console.log(data)

          window.open('/download?path='+data.path)
          $("#button").text("Upload File")
          $("#button").prop("disabled",false);
          location.reload();
      }
          })
      },
      xhr: function() {
        // create an XMLHttpRequest
        var xhr = new XMLHttpRequest();
        // listen to the 'progress' event
        xhr.upload.addEventListener('progress', function(evt) {
          if (evt.lengthComputable) {
            // calculate the percentage of upload completed
            var percentComplete = evt.loaded / evt.total;
            percentComplete = parseInt(percentComplete * 100);
            // update the Bootstrap progress bar with the new percentage
            $('.progress-bar').text(percentComplete + '%');
            $('.progress-bar').width(percentComplete + '%');
            // once the upload reaches 100%, set the progress bar text to done
            if (percentComplete === 100) {
              $('.progress-bar').html('Done');
            }
          }
        }, false);
        return xhr;
      }
    });
  }
}
  </script>
</html>

 

See also  Javascript Income Expense or Budget Tracker or Calculator Using LocalStorage in HTML5 and CSS3 Full Project For Beginners

 

Leave a Reply