如果父文件夹不存在,如何写文件? [英] How to write file if parent folder doesn't exist?
问题描述
fs.writeFile('/ folder1 / folder2 / file.txt ','content',function(){
});
但是 如何将内容写入该路径? 使用 mkdirp 结合 这个模块做你想做的: https:// npmjs .org / package / writefile 。当谷歌搜索writefile mkdirp时得到它。这个模块返回一个promise,而不是回调,所以一定要先阅读promise的一些介绍。这可能会让事情变得复杂。 我给的函数在任何情况下都是可用的。 I need to write file to the following path: But How can I write content to that path? Use mkdirp in combination with If the whole path already exists, This module does what you want: https://npmjs.org/package/writefile . Got it when googling for "writefile mkdirp". This module returns a promise instead of taking a callback, so be sure to read some introduction to promises first. It might actually complicate things for you. The function I gave works in any case. 这篇关于如果父文件夹不存在,如何写文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!'/ folder1 / folder2'
路径可能不存在。所以我得到以下错误:
$ p $ message = ENOENT,打开/folder1/folder2/file.txt
code>
path.dirname
。
var mkdirp = require('mkdirp');
var fs = require('fs');
var getDirName = require('path')。dirname;
$ b $函数writeFile(path,contents,cb){
mkdirp(getDirName(path),function(err){
if(err)return cb(err);
fs.writeFile(path,contents,cb);
});如果整个路径已经存在, mkdirp
是一个noop。否则,它会为您创建所有丢失的目录。
fs.writeFile('/folder1/folder2/file.txt', 'content', function () {
});
'/folder1/folder2'
path may not exists. So I get the following error: message=ENOENT, open /folder1/folder2/file.txt
path.dirname
first.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);
});
}
mkdirp
is a noop. Otherwise it creates all missing directories for you.