extract.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // give it a tarball and a path, and it'll dump the contents
  2. module.exports = Extract
  3. var tar = require("../tar.js")
  4. , fstream = require("fstream")
  5. , inherits = require("inherits")
  6. , path = require("path")
  7. function Extract (opts) {
  8. if (!(this instanceof Extract)) return new Extract(opts)
  9. tar.Parse.apply(this)
  10. if (typeof opts !== "object") {
  11. opts = { path: opts }
  12. }
  13. // better to drop in cwd? seems more standard.
  14. opts.path = opts.path || path.resolve("node-tar-extract")
  15. opts.type = "Directory"
  16. opts.Directory = true
  17. // similar to --strip or --strip-components
  18. opts.strip = +opts.strip
  19. if (!opts.strip || opts.strip <= 0) opts.strip = 0
  20. this._fst = fstream.Writer(opts)
  21. this.pause()
  22. var me = this
  23. // Hardlinks in tarballs are relative to the root
  24. // of the tarball. So, they need to be resolved against
  25. // the target directory in order to be created properly.
  26. me.on("entry", function (entry) {
  27. // if there's a "strip" argument, then strip off that many
  28. // path components.
  29. if (opts.strip) {
  30. var p = entry.path.split("/").slice(opts.strip).join("/")
  31. entry.path = entry.props.path = p
  32. if (entry.linkpath) {
  33. var lp = entry.linkpath.split("/").slice(opts.strip).join("/")
  34. entry.linkpath = entry.props.linkpath = lp
  35. }
  36. }
  37. if (entry.type === "Link") {
  38. entry.linkpath = entry.props.linkpath =
  39. path.join(opts.path, path.join("/", entry.props.linkpath))
  40. }
  41. if (entry.type === "SymbolicLink") {
  42. var dn = path.dirname(entry.path) || ""
  43. var linkpath = entry.props.linkpath
  44. var target = path.resolve(opts.path, dn, linkpath)
  45. if (target.indexOf(opts.path) !== 0) {
  46. linkpath = path.join(opts.path, path.join("/", linkpath))
  47. }
  48. entry.linkpath = entry.props.linkpath = linkpath
  49. }
  50. })
  51. this._fst.on("ready", function () {
  52. me.pipe(me._fst, { end: false })
  53. me.resume()
  54. })
  55. this._fst.on('error', function(err) {
  56. me.emit('error', err)
  57. })
  58. this._fst.on('drain', function() {
  59. me.emit('drain')
  60. })
  61. // this._fst.on("end", function () {
  62. // console.error("\nEEEE Extract End", me._fst.path)
  63. // })
  64. this._fst.on("close", function () {
  65. // console.error("\nEEEE Extract End", me._fst.path)
  66. me.emit("finish")
  67. me.emit("end")
  68. me.emit("close")
  69. })
  70. }
  71. inherits(Extract, tar.Parse)
  72. Extract.prototype._streamEnd = function () {
  73. var me = this
  74. if (!me._ended || me._entry) me.error("unexpected eof")
  75. me._fst.end()
  76. // my .end() is coming later.
  77. }