ファイルが存在する場合と存在しない場合があるディレクトリにある場合、nodejsを使用してファイルを書き込むにはどうすればよいですか?
この質問に似ています:
node.js ディレクトリを含むファイルを書き込みますか?
node-fs はディレクトリのみを作成しますが、ファイルを作成するソリューションが必要なのは私だけです。
ファイルが存在する場合と存在しない場合があるディレクトリにある場合、nodejsを使用してファイルを書き込むにはどうすればよいですか?
この質問に似ています:
node.js ディレクトリを含むファイルを書き込みますか?
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 ();
}
});
};
親フォルダーが存在しない場合にファイルを書き込む方法への回答としてこれを書きましたか? . 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)
})
}
のようなものを使用できますcreateWriteStream
。
ファイルが存在しない場合は、ファイルを作成するだけです。
// 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');
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) {
。
https://github.com/douzi8/file-systemを使用できます
var file = require('file-system');
file.mkdir('1/2/3/4/5', [mode], function(err) {});