dfilatov / vow-fs

Vow-based file I/O for Node.js
MIT License
28 stars 8 forks source link

Support creating tmp files #2

Closed mdevils closed 11 years ago

mdevils commented 11 years ago

Syntax:

vowFs.tmpFile(options);

options = options || {}

options.prefix = options.prefix || '_tmp_';
options.postfix = options.postfix || '.tmp';
options.directory = options.directory || os.tmpdir();
options.generator = options.generator || function(directory, prefix, postfix) {
    return directory + '/' + prefix + (+new Date()) + (Math.random() * 0x1000000000).toString(36) + postfix;
}

Example implementation (didn't test):

    tmpFile: function(options) {
        options = options || {}

        options.prefix = options.prefix || '_tmp_';
        options.postfix = options.postfix || '.tmp';
        options.directory = options.directory || os.tmpdir();
        options.generator = options.generator || function(directory, prefix, postfix) {
            return directory + '/' + prefix + (+new Date()) + (Math.random() * 0x1000000000).toString(36) + postfix;
        };
        function createTmpFilename() {
            var filename = options.generator(options.directory, options.prefix, options.postfix),
                promise = Vow.promise();
            fs.exists(filename, function(exists) {
                if (exists) {
                    return createTmpFilename(options).then(function(filename) {
                        promise.fulfill(filename);
                    }, function(err) {
                        promise.reject(err);
                    });
                } else {
                    vowFs.write(filename, '').then(function() {
                        promise.fulfill(filename)
                    }, function(err) {
                        promise.reject(err);
                    });
                }
            });
            return promise;
        }
        return createTmpFilename();
    }
dfilatov commented 11 years ago

Added in 0.1.9