node.js递归写文件目录

Har*_*rry 4 node.js

如果文件位于可能存在或不存在的目录中,如何使用nodejs编写文件?

它有点类似于这个问题:

node.js用目录写文件?

只有我需要一个创建文件的解决方案,而node-fs只生成目录.

Gab*_*mas 5

来自FileUtils:

修改功能以满足您的需求!但严重的是,使用模块而不是编写自己的模块!

createDirectory():创建一个目录.如果不存在构成路径的任何先前目录,则会创建它们.默认权限:0777.

File.prototype.createDirectory = function (cb){
    if (cb) cb = cb.bind (this);
    if (!this._path){
        if (cb) cb (NULL_PATH_ERROR, false);
        return;
    }
    if (!canWriteSM (this._usablePath)){
        if (cb) cb (SECURITY_WRITE_ERROR, false);
        return;
    }

    var mkdirDeep = function (path, cb){
        path.exists (function (exists){
            if (exists) return cb (null, false);

            FS.mkdir (path.getPath (), function (error){
                if (!error) return cb (null, true);

                var parent = path.getParentFile ();
                if (parent === null) return cb (null, false);

                mkdirDeep (parent, function (error, created){
                    if (created){
                        FS.mkdir (path.getPath (), function (error){
                            cb (error, !error);
                        });
                    }else{
                        parent.exists (function (exists){
                            if (!exists) return cb (null, false);

                            FS.mkdir (path.getPath (), function (error){
                                cb (error, !error);
                            });
                        });
                    }
                });
            });
        });
    };

    mkdirDeep (this.getAbsoluteFile (), function (error, created){
        if (cb) cb (error, created);
    });
};
Run Code Online (Sandbox Code Playgroud)

createNewFile():创建一个新文件.默认权限:0666.

File.prototype.createNewFile = function (cb){
    if (cb) cb = cb.bind (this);
    if (!this._path){
        if (cb) cb (NULL_PATH_ERROR, false);
        return;
    }

    if (!canWriteSM (this._usablePath)){
        if (cb) cb (SECURITY_WRITE_ERROR, false);
        return;
    }

    var path = this._usablePath;
    PATH.exists (path, function (exists){
        if (exists){
            if (cb) cb (null, false);
        }else{
            var s = FS.createWriteStream (path);
            s.on ("error", function (error){
                if (cb) cb (error, false);
            });
            s.on ("close", function (){
                if (cb) cb (null, true);
            });
            s.end ();
        }
    });
};
Run Code Online (Sandbox Code Playgroud)