Javascript 在 Node.js 中写入文件时创建目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13542667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:19:20  来源:igfitidea点击:

Create Directory When Writing To File In Node.js

javascriptnode.js

提问by Hirvesh

I've been tinkering with Node.js and found a little problem. I've got a script which resides in a directory called data. I want the script to write some data to a file in a subdirectory within the datasubdirectory. However I am getting the following error:

我一直在修改 Node.js,发现了一个小问题。我有一个脚本,它驻留在名为data. 我希望脚本将一些数据写入子目录中子目录中的文件data。但是我收到以下错误:

{ [Error: ENOENT, open 'D:\data\tmp\test.txt'] errno: 34, code: 'ENOENT', path: 'D:\data\tmp\test.txt' }

The code is as follows:

代码如下:

var fs = require('fs');
fs.writeFile("tmp/test.txt", "Hey there!", function(err) {
    if(err) {
        console.log(err);
    } else {
        console.log("The file was saved!");
    }
}); 

Can anybody help me in finding out how to make Node.js create the directory structure if it does not exits for writing to a file?

任何人都可以帮助我找出如何让 Node.js 创建目录结构,如果它不退出写入文件?

采纳答案by David Weldon

Node > 10.12.0

节点 > 10.12.0

fs.mkdirnow accepts a { recursive: true }option like so:

fs.mkdir现在接受这样的{ recursive: true }选项:

// Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist.
fs.mkdir('/tmp/a/apple', { recursive: true }, (err) => {
  if (err) throw err;
});

or with a promise:

或承诺:

fs.promises.mkdir('/tmp/a/apple', { recursive: true }).catch(console.error);

Node <= 10.11.0

节点 <= 10.11.0

You can solve this with a package like mkdirpor fs-extra. If you don't want to install a package, please see Tiago Peres Fran?a's answer below.

您可以使用mkdirpfs-extra 之类的包来解决此问题。如果您不想安装软件包,请参阅下面的 Tiago Peres Fran?a 的回答。

回答by Tiago Peres Fran?a

If you don't want to use any additional package, you can call the following function before creating your file:

如果您不想使用任何额外的包,您可以在创建文件之前调用以下函数:

var path = require('path'),
    fs = require('fs');

function ensureDirectoryExistence(filePath) {
  var dirname = path.dirname(filePath);
  if (fs.existsSync(dirname)) {
    return true;
  }
  ensureDirectoryExistence(dirname);
  fs.mkdirSync(dirname);
}

回答by lifeisfoo

With node-fs-extrayou can do it easily.

使用node-fs-extra,您可以轻松完成。

Install it

安装它

npm install --save fs-extra

Then use the outputFilemethod. Its documentation says:

然后使用outputFile方法。它的文档说:

Almost the same as writeFile (i.e. it overwrites), except that if the parent directory does not exist, it's created.

几乎与 writeFile 相同(即覆盖),除了如果父目录不存在,则创建它。

You can use it in three ways:

您可以通过三种方式使用它:

Callback style

回调样式

const fse = require('fs-extra');

fse.outputFile('tmp/test.txt', 'Hey there!', err => {
  if(err) {
    console.log(err);
  } else {
    console.log('The file was saved!');
  }
})

Using Promises

使用承诺

If you use promises, and I hope so, this is the code:

如果你使用promises,我希望如此,这是代码:

fse.outputFile('tmp/test.txt', 'Hey there!')
   .then(() => {
       console.log('The file was saved!');
   })
   .catch(err => {
       console.error(err)
   });

Sync version

同步版本

If you want a sync version, just use this code:

如果您想要同步版本,只需使用以下代码:

fse.outputFileSync('tmp/test.txt', 'Hey there!')

For a complete reference, check the outputFiledocumentationand all node-fs-extra supported methods.

如需完整参考,请查看outputFile文档和所有node-fs-extra 支持的方法

回答by jrajav

Shameless plug alert!

无耻的插头警报!

You will have to check for each directory in the path structure you want and create it manually if it doesn't exist. All the tools to do so are already there in Node's fs module, but you can do all of that simply with my mkpath module: https://github.com/jrajav/mkpath

您必须检查所需路径结构中的每个目录,如果不存在则手动创建。Node 的 fs 模块中已经提供了所有这样做的工具,但您只需使用我的 mkpath 模块即可完成所有这些操作:https: //github.com/jrajav/mkpath

回答by micx

Since I cannot comment yet, I'm posting an enhanced answer based on @tiago-peres-fran?a fantastic solution (thanks!). His code does not make directory in a case where only the last directory is missing in the path, e.g. the input is "C:/test/abc" and "C:/test" already exists. Here is a snippet that works:

由于我还不能发表评论,我发布了一个基于@tiago-peres-fran 的增强答案?一个很棒的解决方案(谢谢!)。在路径中只缺少最后一个目录的情况下,他的代码不会创建目录,例如输入是“C:/test/abc”并且“C:/test”已经存在。这是一个有效的片段:

function mkdirp(filepath) {
    var dirname = path.dirname(filepath);

    if (!fs.existsSync(dirname)) {
        mkdirp(dirname);
    }

    fs.mkdirSync(filepath);
}

回答by Alex C.

My advise is: try not to rely on dependencies when you can easily do it with few lines of codes

我的建议是:当你可以用几行代码轻松做到时,尽量不要依赖依赖项

Here's what you're trying to achieve in 14lines of code:

这是您试图在14行代码中实现的目标:

fs.isDir = function(dpath) {
    try {
        return fs.lstatSync(dpath).isDirectory();
    } catch(e) {
        return false;
    }
};
fs.mkdirp = function(dirname) {
    dirname = path.normalize(dirname).split(path.sep);
    dirname.forEach((sdir,index)=>{
        var pathInQuestion = dirname.slice(0,index+1).join(path.sep);
        if((!fs.isDir(pathInQuestion)) && pathInQuestion) fs.mkdirSync(pathInQuestion);
    });
};

回答by Kev

I just published this module because I needed this functionality.

我刚刚发布了这个模块,因为我需要这个功能。

https://www.npmjs.org/package/filendir

https://www.npmjs.org/package/filendir

It works like a wrapper around Node.js fs methods. So you can use it exactly the same way you would with fs.writeFileand fs.writeFileSync(both async and synchronous writes)

它的工作原理类似于 Node.js fs 方法的包装器。所以你可以像使用fs.writeFileand一样使用它fs.writeFileSync(异步和同步写入)