node.js递归写入文件目录

标签 node.js

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

这有点类似于这个问题:

node.js Write file with directories?

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

最佳答案

来自 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);
    });
};

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 ();
        }
    });
};

关于node.js递归写入文件目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10731899/

相关文章:

json - 在 NodeJS 中将 Protobuf 响应转换为 JSON

node.js - Node Express 设计用于避免 Socket.io 中的多个客户端

node.js - mongodb中只查询整数

node.js - 使用 Node Canvas 操作远程图像时出错 : "Image given has not completed loading"

node.js - 合并聚合并在 MongoDB 中查找结果

javascript - 在此模块外的 Node.js 模块中模拟构造函数(或其他函数)

javascript - Angular 2 + Zone.js + Common js 模块 : IF statement anomaly, 代码即使在错误情况下也会执行

javascript - Node ffi 指向结构体的指针

node.js - 防止导入 es6 默认导出

node.js - Centos 7安装strongloop报错