1

I'm creating a class in a separate file to import from the controller, but it won't let me declare variables inside the class.

This is the class I want to export:

const fs = require("fs");
const rimraf = require("rimraf");

export class createDir {
    let dir = 'src/output';
    if (fs.existsSync(dir)) {
        rimraf.sync(dir);
    }else {
        fs.mkdirSync(dir);
     }
}

This is the error that let shows:

Unexpected token. A constructor, method, accessor, or property was expected

My problem: how can I export the function in Typescript and what is the problem?

4
  • Welcome to SO! If your original question is answered but you have further unrelated questions, it is best to mark that answer as correct then start a new question instead of taking on new questions. This keeps questions focused and easier to search for.
    – Jeff B
    Commented Jun 7, 2021 at 15:48
  • @JeffB The question goes inside the original question is just knowing how to get that name because I don't understand why it returns undefined
    – menphis
    Commented Jun 7, 2021 at 15:51
  • I will reply to your question, but understanding how to correctly reference imported classes and functions IS a separate issue to knowing how to export classes and functions =).
    – Jeff B
    Commented Jun 7, 2021 at 15:55
  • @JeffB Ok I understand, I will better review my questions, thank you. Can you solve just this last question for me to close the question? I am still somewhat stuck
    – menphis
    Commented Jun 7, 2021 at 15:58

1 Answer 1

2

You need a function in your class:

export class createDir {
  function checkExistsOrCreate () {
    let dir = 'src/output';
    if (fs.existsSync(dir)) {
        rimraf.sync(dir);
    }else {
        fs.mkdirSync(dir);
     } 
  }
}
3
  • Ok, and now how do I export and import in another class, that is, how can I execute this function in another class?
    – menphis
    Commented Jun 7, 2021 at 15:16
  • I think you want your class to be a function, or the class should be called something like file. To import in another file, you would import {createDir} from "createDirFile" To use it, you would do let x = new createDir(); x.checkExistsOrCreate() Commented Jun 7, 2021 at 15:22
  • I have a problem now, I have added the following: let dir = new createDir (). CheckExistsOrCreate (); but it returns me undefined, how can I read the created src / output folder?
    – menphis
    Commented Jun 7, 2021 at 15:32

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.