summaryrefslogtreecommitdiffstats
path: root/lib/fs/node.js
diff options
context:
space:
mode:
authorSamy Pessé <samypesse@gmail.com>2016-01-22 21:04:36 +0100
committerSamy Pessé <samypesse@gmail.com>2016-01-22 21:04:36 +0100
commit877f2e477b010f9f37a9044606f110a90f077680 (patch)
tree5cd61cf3b00ba10dc6110535ed9fdf67d8baba72 /lib/fs/node.js
parentc8e2fc0e57d223c01a51d6ee186fc1662cd74d13 (diff)
downloadgitbook-877f2e477b010f9f37a9044606f110a90f077680.zip
gitbook-877f2e477b010f9f37a9044606f110a90f077680.tar.gz
gitbook-877f2e477b010f9f37a9044606f110a90f077680.tar.bz2
Start rewrite
Diffstat (limited to 'lib/fs/node.js')
-rw-r--r--lib/fs/node.js72
1 files changed, 72 insertions, 0 deletions
diff --git a/lib/fs/node.js b/lib/fs/node.js
new file mode 100644
index 0000000..0c470d7
--- /dev/null
+++ b/lib/fs/node.js
@@ -0,0 +1,72 @@
+var Q = require('q');
+var _ = require('lodash');
+var util = require('util');
+var path = require('path');
+var fs = require('fs');
+
+var BaseFS = require('./');
+
+function NodeFS() {
+ BaseFS.call(this);
+}
+util.inherits(NodeFS, BaseFS);
+
+// Check if a file exists, run a Promise(true) if that's the case, Promise(false) otherwise
+NodeFS.prototype.exists = function(filename) {
+ var d = Q.defer();
+
+ fs.exists(filename, function(exists) {
+ d.resolve(exists);
+ });
+
+ return d.promise;
+};
+
+// Read a file and returns a promise with the content as a buffer
+NodeFS.prototype.read = function(filename) {
+ return Q.nfcall(fs.readFile, filename);
+};
+
+// Write a file and returns a promise
+NodeFS.prototype.write = function(filename, buffer) {
+ return Q.nfcall(fs.writeFile, filename, buffer);
+};
+
+// List files in a directory
+NodeFS.prototype.readdir = function(folder) {
+ return Q.nfcall(fs.readdir, folder)
+ .then(function(files) {
+ return _.chain(files)
+ .map(function(file) {
+ if (file == '.' || file == '..') return;
+
+ var stat = fs.statSync(path.join(folder, file));
+ if (stat.isDirectory()) file = file + path.sep;
+ return file;
+ })
+ .compact()
+ .value();
+ });
+};
+
+// Load a JSON/JS file
+NodeFS.prototype.loadAsObject = function(filename) {
+ return Q()
+ .then(function() {
+ var jsFile;
+
+ try {
+ jsFile = require.resolve(filename);
+
+ // Invalidate node.js cache for livreloading
+ delete require.cache[jsFile];
+
+ return require(jsFile);
+ }
+ catch(err) {
+ return Q.reject(err);
+ }
+ });
+};
+
+module.exports = NodeFS;