Browse Source

copy now works if destination directory does not exist when copying file

ci/travis-osximage
JP Richardson 11 years ago
parent
commit
d9a60558c9
  1. 25
      lib/copy.js
  2. 20
      test/copy.test.js

25
lib/copy.js

@ -1,7 +1,9 @@
"use strict"
var fs = require('fs')
, ncp = require('ncp').ncp;
, ncp = require('ncp').ncp
, path = require('path')
, mkdir = require('./mkdir')
var BUF_LENGTH = 64 * 1024;
var _buff = new Buffer(BUF_LENGTH);
@ -31,11 +33,26 @@ var copyFile = function(srcFile, destFile, cb) {
return fdr.pipe(fdw);
};
function copy(source, dest, callback) {
if (callback)
function copy(src, dest, callback) {
callback = callback || function(){}
fs.lstat(src, function(err, stats) {
if (err) callback(err)
if (!stats.isFile()) return ncp(src, dest, callback)
var dir = path.dirname(dest)
fs.exists(dir, function(dirExists) {
if (dirExists) return ncp(src, dest, callback)
mkdir.mkdirs(dir, function(err) {
if (err) return callback(err)
ncp(src, dest, callback)
})
})
})
/*if (callback)
ncp(source, dest, callback);
else
ncp(source, dest, function(){});
ncp(source, dest, function(){});*/
};

20
test/copy.test.js

@ -8,9 +8,10 @@ var SIZE = 16 * 64 * 1024 + 7;
var DIR = '';
describe('fs-extra', function() {
beforeEach(function(done) {
beforeEach(function() {
DIR = testutil.createTestDir('fs-extra');
done();
//DIR = path.join(DIR, 'copy')
//mkdir.sync(DIR)
})
afterEach(function(done) {
@ -46,8 +47,21 @@ describe('fs-extra', function() {
done()
})
})
})
describe('> when the destination dir does not exist', function() {
it('should create the destination directory and copy the file', function(done) {
var src = path.join(DIR, 'file.txt')
var dest = path.join(DIR, 'this/path/does/not/exist/copied.txt')
var data = "did it copy?\n"
fs.writeFileSync(src, data, 'utf8')
fs.copy(src, dest, function(err) {
done(err)
})
})
})
})
describe('> when the source is a directory', function() {
it('should copy the directory asynchronously', function(done) {

Loading…
Cancel
Save