如果父文件夹不存在,如何写文件? [英] How to write file if parent folder doesn't exist?

查看:218
本文介绍了如果父文件夹不存在,如何写文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  fs.writeFile('/ folder1 / folder2 / file.txt ','content',function(){

});

但是'/ folder1 / folder2'路径可能不存在。所以我得到以下错误:

$ p $ message = ENOENT,打开/folder1/folder2/file.txt
code>

如何将内容写入该路径?

解决方案

使用 mkdirp 结合 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。否则,它会为您创建所有丢失的目录。

这个模块做你想做的: https:// npmjs .org / package / writefile 。当谷歌搜索writefile mkdirp时得到它。这个模块返回一个promise,而不是回调,所以一定要先阅读promise的一些介绍。这可能会让事情变得复杂。



我给的函数在任何情况下都是可用的。

I need to write file to the following path:

 fs.writeFile('/folder1/folder2/file.txt', 'content', function () {

 });

But '/folder1/folder2' path may not exists. So I get the following error:

 message=ENOENT, open /folder1/folder2/file.txt

How can I write content to that path?

解决方案

Use mkdirp in combination with 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);
  });
}

If the whole path already exists, mkdirp is a noop. Otherwise it creates all missing directories for you.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆