Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create tar file from files in a particular directory

Tags:

node.js

I need to use nodejs to create a tar file that isn't encompassed in a parent directory.

For example, here is the file system:

/tmp/mydir
/tmp/mydir/Dockerfile
/tmp/mydir/anotherfile

What I'm looking to do is the equivalent to this:

cd /tmp/mydir
tar -cvf archive.tar *

So, when I extract archive.tar, Dockerfile will end up in the same directory I execute the command.

I've tried tar.gz and a few others, but all the examples are compressing an entire directory, and not just files.

I'm doing this so I can utilize the Docker REST API to send builds.

like image 840
Coder1 Avatar asked Sep 09 '14 05:09

Coder1


People also ask

Can we tar a directory?

Tape Archive or tar is a file format for creating files and directories into an archive while preserving filesystem information such as permissions. We can use the tar command to create tar archives, extract the archives, view files and directories stored in the archives, and append files to an existing archive.


2 Answers

With a modern module node-tar you can create a .tar file like this:

tar.create(
    { file: 'archive.tar' },
    ['/tmp/mydir']
).then(_ => { .. tarball has been created .. })

The tar.gz module referenced in other answers is deprecated.

like image 61
kelin Avatar answered Nov 30 '22 13:11

kelin


Use tar.gz module. Here is a sample code

var targz = require('tar.gz');
var compress = new targz().compress('/path/to/compress', '/path/to/store.tar.gz',
function(err){
         if(err)
         console.log(err);
         console.log('The compression has ended!');
});

For more options, visit the documentation page.

This package is now deprecated. Check the answer provided by @Kelin.

like image 36
Ravi Avatar answered Nov 30 '22 13:11

Ravi