Skip to content

Instantly share code, notes, and snippets.

@soldair
Last active February 14, 2019 21:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soldair/ef88083adf7e96801efd31cd8f72e923 to your computer and use it in GitHub Desktop.
Save soldair/ef88083adf7e96801efd31cd8f72e923 to your computer and use it in GitHub Desktop.
easiest way to create a tarball with a file called seahorse.txt with the contents and attributes of a file called file.txt
//@ts-check
// easiest way to create a tarball with a file called seahorse.txt
// with the contents and attributes of a file called file.txt
let Header = require('tar/lib/header')
let ReadEntry = require('tar/lib/read-entry')
let Pack = require('tar/lib/pack.js')
let modeFix = require('tar/lib/mode-fix')
let fs = require('fs')
// target file name
let path = __dirname+'/file.txt'
// get the stat
let stat = fs.statSync(path)
// change the stat into a header and make a read entry form the header
let entry = pathToReadEntry({path,toPath:'/seahorse.txt',stat})
// create a new Pack
let pack = new Pack({gzip:false})
// write the entry
pack.write(entry)
// when the entry is done end the pack.
entry.on('end',()=>{
pack.end()
})
// write it to a file.
pack.pipe(fs.createWriteStream('./test.tar'))
function pathToReadEntry(opts){
const {path,toPath,linkpath,stat} = opts
let myuid = process.getuid && process.getuid()
let myuser = process.env.USER || ''
// settings.
//override mtime.
let mtime = false;
// dont write an mtime
let noMtime = true;
// dont write anything other than size, linkpath, path and mode
let portable = true;
let header = new Header({
path: toPath || path,
// if this is a link. the path the link points to.
linkpath: linkpath,
mode: modeFix(stat.mode,stat.isDirectory()),
uid: portable ? null : stat.uid,
gid: portable ? null : stat.gid,
size: stat.size,
mtime: noMtime ? null : mtime || stat.mtime,
type: statToType(stat),
uname: portable ? null :
stat.uid === myuid ? myuser : '',
atime: portable ? null : stat.atime,
ctime: portable ? null : stat.ctime
})
let entry = new ReadEntry(header)
fs.createReadStream(path).pipe(entry)
return entry
}
function statToType(stat){
if(stat.isDirectory()) return 'Directory'
if(stat.isSymbolicLink()) return 'SymbolicLink'
if(stat.isFile()) return 'File'
// return nothing if unsupported.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment