简体   繁体   English

检查typescript中是否存在文件

[英]Check if a file exists in typescript

I am new to typescript and need to check if a certain system is installed on the machine, which is windows. 我是打字稿的新手,需要检查机器上是否安装了某个系统,即windows。 I'm thinking of doing this by checking for the existence of some files, but I'm not finding how to do this check in typescript. 我想通过检查一些文件的存在来做到这一点,但我没有找到如何检查打字稿。 Would anyone have any idea how to do it? 有人会知道怎么做吗?

fs.stat(path, (exists) => {
            if (exists == null) {
                return true;
            } else if (exists.code === 'ENOENT') {
                return false;
            }
        });

This one works for me 这个对我有用

  let file = 'ObjectCreatorBundles'; fs.exists(file, (exist) => { if (exist) { console.log("I got your file") } else { console.log("the file doesn't exists"); } }); 

  1. Install file-exists from npm (eg npm install file-exists --save) 从npm安装文件存在(例如npm install file-exists --save)
  2. fileExists('your file name', (err, exists) => console.log(exists)) fileExists('你的文件名',(错误,存在)=> console.log(存在))
  3. Returns true if filepath exists and is a file 如果filepath存在且文件是,则返回true

I found this approach much simpler: 我发现这种方法更简单:

import fs from 'fs';
if (fs.existsSync(path)) {
  // File exists in path
} else {
  // File doesn't exist in path
}

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

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