Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Add fs.writeFile

  • Loading branch information...
commit 65b1e4bc2e67787b2892e373398b1ed3f96fdc0d 1 parent 5442764
@vojtajina authored
Showing with 48 additions and 0 deletions.
  1. +20 −0 lib/fs.js
  2. +28 −0 test/fs.spec.coffee
View
20 lib/fs.js
@@ -1,7 +1,9 @@
// TODO(vojta): allow relative paths
var util = require('util');
+var path = require('path');
var predictableNextTick = require('./util.js').predictableNextTick;
+
/**
* @constructor
* @param {boolean} isDirectory
@@ -34,6 +36,8 @@ var File = function(mtime, content) {
var Mock = function(structure) {
var watchers = {};
+ // TODO(vojta): convert structure to contain only instances of File/Directory (not primitives)
+
var getPointer = function(path, pointer) {
var parts = path.split('/').slice(1);
@@ -116,6 +120,22 @@ var Mock = function(structure) {
return new Buffer('');
};
+ this.writeFile = function(filePath, content, callback) {
+ predictableNextTick(function() {
+ var pointer = getPointer(path.dirname(filePath), structure);
+ var baseName = path.basename(filePath);
+
+ if (pointer && typeof pointer === 'object' && !(pointer instanceof File)) {
+ pointer[baseName] = new File(0, content);
+ callback(null);
+ } else {
+ var error = new Error(util.format('Can not open "%s"', filePath));
+ error.code = 'ENOENT';
+ callback(error);
+ }
+ });
+ };
+
this.watchFile = function(path, options, callback) {
callback = callback || options;
watchers[path] = watchers[path] || [];
View
28 test/fs.spec.coffee
@@ -188,6 +188,34 @@ describe 'fs', ->
toThrow 'Illegal operation on directory'
+ # ===========================================================================
+ # fs.writeFile
+ # ===========================================================================
+ describe 'writeFile', ->
+
+ it 'should write file content as Buffer', ->
+ callback = (err) ->
+ expect(err).toBeFalsy()
+ finished++
+
+ fs.writeFile '/home/vojta/some.js', 'something', callback
+ waitForFinished()
+
+ runs ->
+ expect(fs.readFileSync('/home/vojta/some.js').toString()).toBe 'something'
+
+
+ it 'should return ENOENT when writing to non-existing directory', ->
+ callback = (err) ->
+ expect(err).toBeTruthy()
+ expect(err instanceof Error).toBe true
+ expect(err.code).toBe 'ENOENT'
+ finished++
+
+ fs.writeFile '/home/vojta/non/existing/some.js', 'something', callback
+ waitForFinished()
+
+
# ===========================================================================
# fs.watchFile
# ===========================================================================
Please sign in to comment.
Something went wrong with that request. Please try again.