Zip directory using Node.JS

Archiving a file/folder using nodejs is very simple. I have used nodejs archiver library to zip directory and fs library to get the file information in this post.

const fs = require('fs');
var archiver = require('archiver');

function zip_directory(filename, copyFrom, copyToPath){
    var copyTo = copyToPath + filename;

    if(!fs.existsSync(copyToPath)){
        fs.mkdirSync(copyToPath);
    }

    var output = fs.createWriteStream(copyTo);
    var archive = archiver('zip', {
      zlib: { level: 9 } // Sets the compression level.
    });

    output.on('close', function () {
        console.log(`\n<< ARCHIVE LOG: TOTAL BYTES ${archive.pointer()} >>`);
        console.log(`\n<< ARCHIVE LOG: archiver has been finalized and the output file descriptor has closed. >>`);
    });

    output.on('end', function() {
	  console.log(`\n<< ARCHIVE LOG: END : Data has been drained. >>`);
	});

    archive.on('warning', function(err) {
	  if (err.code === 'ENOENT') {
	    console.log(`\n<< ARCHIVE LOG: ENOENT ${err} >>`);
	  } else {
	    console.log(`\n<< ARCHIVE LOG: WARNING ${err} >>`);
	  }
	});

    archive.on('error', function(err){
        console.log(`\n<< ARCHIVE LOG: Error : ${err} >>`);
    });

    try {
        archive.pipe(output);
        archive.directory(copyFrom, { name: filename });
        archive.finalize();
    } catch (err) {
        console.log(`\n<< ARCHIVE LOG: Error : ${err} >>`);
    }
}


zip_directory('myzipfile.zip', '/home/', '/opt/zipfiles/');

 

Note: Should install required packages as well as declare require things in code.

Tagged : / /

NodeJs Http Server (Web Server)

Making a simple HTTP server in Node.js is very simple. Node.js provides extremely easy-to-use HTTP APIs, a simple web server.

Let’s take a look at a very simple example:

const http = require('http');

const http_port = 8000;

// Instantiate the HTTP server.
const httpServer = http.createServer((req, res) => {
    if (req.method == 'POST') {
        var jsonString = '';

        req.on('data', function (data) {
    	    try {
                console.log(data.toString());
    	    }
    	    catch(err) {
    		console.log(err);
    	    }
        });

      	req.on('error', (err) => {
            // This prints the error message and stack trace to `stderr`.
            console.log("POST ERROR \n" + err.stack);
      	});

        req.on('end', function () {
             console.log('POST Request ended here.');
        });
    }
    
    res.writeHead(200);
    res.end();
    console.log('Response ended here. \n ');
});


httpServer.listen(http_port, () => {
  console.log("Web server is listening on port %s \n", http_port);
});

Save this in a file called server.js – run node server.js, and your programĀ  will hang there… it’s waiting for connections to respond to, so you’ll have to give it one if you want to see it do anything. If everything has been set up correctly, you should see your server’s request & response log.

Let’s take a more in-depth look at what the above code is doing. Function in http.createServer takes a request object and a response object as parameters.

The request object contains things such as the requested URL, Request Method and data.

The response object is how we send the headers and contents of the response back to the user making the request. Here we return a 200 response code (signaling a successful response) with empty body. Other headers, such as Content-type, would also be set here.

The listen method, which causes the server to wait for incoming requests on the specified port – 8000, in this case.

There you have it – your most basic Node.js HTTP server.