Reputation: 13321
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.
Upvotes: 5
Views: 14751
Reputation: 1360
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!');
});
This package is now deprecated. Check the answer provided by @Kelin.
Upvotes: 2
Reputation: 11985
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.
Upvotes: 6
Reputation: 2794
Second argument to the constructor is passed on as properties to the tar module.
var TarGz = require('tar.gz');
var compressor = new TarGz({}, {fromBase: true});
This will use create the archive without top level directory.
Edit: This was undocumented in node-tar.gz
but pull request has now been merged: https://github.com/alanhoff/node-tar.gz#tar-options
Upvotes: 1