简体   繁体   English

确定路径是否有效的JavaScript

[英]Determine if path is valid javascript

I have a path which is passed down to me as a javascript variable, which will reference to an image (maybe). 我有一个路径作为JavaScript变量传递给我,该变量将引用图像(也许)。 ../app/assets/icon.png . ../app/assets/icon.png In the case that the path is invalid or doesn't exist, I want to use a different file, located somewhere else. 在路径无效或不存在的情况下,我想使用其他位置的其他文件。 In the end, it should look something like this: 最后,它应该看起来像这样:

var verifiedPath = existsAndIsValid(path) ? path : '../app/default/icon.png'

Is there a simple one-liner in which I can do this? 有没有一个简单的单线可在其中执行此操作?

The very simple exists function is deprecated and recommends using stat or access instead. 不建议使用非常简单的exist函数,建议改用stataccess They are all core NodeJS. 它们都是核心NodeJS。

fs.access('path', fs.R_OK, (err) => {
  if (!err) { console.log("File exists");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM