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. 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 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 =). 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 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);
     } 
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Ok, and now how do I export and import in another class, that is, how can I execute this function in another class?
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()
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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.