How do I read a file's contents?

According to the API documentation I should be able to use a File object to read something from the local filesystem with readline(). At least from what I understand. I attempted a simple test with my Rubocop extension:

const rubyVersion = File.readline(
            `${nova.workspace.path}/.ruby_version`
          );
          options.args.unshift("rvm-exec", rubyVersion, "bundle", "exec");

Which errors with:

Rubocop error: ReferenceError: Can't find variable: File

The same thing occurs if I try something like:

let rubyVersionFile = new File();
          rubyVersionFile.path = `${nova.workspace.path}/.ruby_version`;
          const rubyVersion = rubyVersionFile.readline();
          options.args.unshift("rvm-exec", rubyVersion, "bundle", "exec");

This might be more of a newbie JavaScript question, but I am wondering if someone can point me to a working code example of using the linked File object.

Hello Matt,

You’ll need to create an instance of a file using the nova.fs.open(path, mode) API (documented here). You pass in the path to be opened and the file mode, which if you’re just reading can be r.

Then you’ll have a File instance which you can use .readline() (repeatedly if wanted) as you are in your second attempt.

This was helpful. Thank you. I have now shipped v.1.3.1 of my Rubocop extension as a result of this post and can use it with more of my apps than the ones I’ve updated to the latest Ruby.

1 Like