6

ファイルが存在する場合と存在しない場合があるディレクトリにある場合、nodejsを使用してファイルを書き込むにはどうすればよいですか?

この質問に似ています:

node.js ディレクトリを含むファイルを書き込みますか?

node-fs はディレクトリのみを作成しますが、ファイルを作成するソリューションが必要なのは私だけです。

4

7 に答える 7

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

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 ();
        }
    });
};
于 2012-05-24T13:39:15.287 に答える
3

親フォルダーが存在しない場合にファイルを書き込む方法への回答としてこれを書きましたか? . Googleでこれに出くわした人に役立つかもしれません:

mkdirpを firstと組み合わせて使用​​しpath.dirnameます。

var mkdirp = require("mkdirp")
var fs = require("fs")
var getDirName = require("path").dirname
function writeFile (path, contents, cb) {
  mkdirp(getDirName(path), function (err) {
    if (err) return cb(err)
    fs.writeFile(path, contents, cb)
  })
}
于 2013-05-01T12:08:56.067 に答える
0

のようなものを使用できますcreateWriteStream

ファイルが存在しない場合は、ファイルを作成するだけです。

于 2012-05-24T06:02:48.613 に答える
0
// Create parentDir recursively if it doesn't exist!
const parentDir = 'path/to/parent';
parentDir.split('/').forEach((dir, index, splits) => {
  const curParent = splits.slice(0, index).join('/');
  const dirPath = path.resolve(curParent, dir);
  if (!fs.existsSync(dirPath)) {
    fs.mkdirSync(dirPath);
  }
});

// Create file.js inside the parentDir
fs.writeFileSync(`${parentDir}/file.js`, 'file Content', 'utf8');
于 2016-11-18T22:38:06.253 に答える
0

TypeScript ユーザー向けに、 mkdirPに基づいて作成したものを次に示します。

const _0777 = parseInt('0777', 8);

export function mkdirP(dir: string, opts: {
    fs?: {
        mkdir: (path: string | Buffer, mode: number,
                callback?: (err?: NodeJS.ErrnoException) => void) => void,
        stat: (path: string | Buffer,
               callback?: (err: NodeJS.ErrnoException,
                           stats: fs.Stats) => any) => void
    }, mode?: number}, f: Function, made?) {
    dir = resolve(dir);
    if (typeof opts === 'function') {
        f = <Function>opts;
        opts = {};
    }
    else if (!opts || typeof opts !== 'object')
        opts = {mode: <number>opts};

    opts.mode = opts.mode || (_0777 & (~process.umask()));
    opts.fs = opts.fs || fs;

    if (!made) made = null;

    const cb = f || (() => undefined);

    opts.fs.mkdir(dir, opts.mode, function (error) {
        if (!error) {
            made = made || dir;
            return cb(null, made);
        }
        switch (error.code) {
            case 'ENOENT':
                mkdirP(dirname(dir), opts, function (err, made) {
                    if (err) cb(err, made);
                    else mkdirP(dir, opts, cb, made);
                });
                break;

            default:
                opts.fs.stat(dir, function (e, stat) {
                    if (e || !stat.isDirectory()) cb(error || e, made);
                    else cb(null, made);
                });
        }
    });
}

JavaScript バージョンでは、署名から型注釈を削除するだけです。つまり、最初の数行を次のように変更します(dir, opts, mode, f, made) {

于 2016-05-29T09:42:34.713 に答える
-2

https://github.com/douzi8/file-systemを使用できます

var file = require('file-system');
file.mkdir('1/2/3/4/5', [mode], function(err) {});
于 2014-12-01T14:46:04.357 に答える