5

Using babel-cli you could easily write some node-executable using es2015 syntax. For that you just need to add proper shebang #!/usr/bin/env babel-node.

For example,

#!/usr/bin/env babel-node

import fs from 'fs';

fs.readFileSync('./some-file.csv');

I am wondering how to do that using TypeScript?

UPDATE: Tried ts-node - getting awkward errors even for HelloWorld examples like

const say = (word: string) => {
    console.log(word);
}

say('hello');

it does not work via ts-node test.ts or using #!/usr/bin/env ts-node;

In both cases i'm getting

SyntaxError: Unexpected token :
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at Object.<anonymous> (/usr/local/lib/node_modules/ts-node/src/bin/ts-node.ts:110:12)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)

UPDATE Made ts-node work. It works only if file has .ts extension. For files without extension but with shebang - it does not work. Created github issue for the project that reflects needed behavior.

2 Answers 2

6

I believe you are looking for ts-node.

#!/usr/bin/env ts-node

...rest of script

Author confirms this usage working here: https://github.com/TypeStrong/ts-node/issues/73

p.s. I'd call that an executable, not a binary.

Sign up to request clarification or add additional context in comments.

2 Comments

I tried that yesterday, but apparently it does not work with non-helloworld examples...
If you import other modules and want to be able to call the script from outside the project directory, have a look at my answer to a similar question and this GitHub issue, which goes into more detail.
1

Just to note things have moved on since the approach tried by @ValeriiVasin and the one recommended in @Paarth's answer.

Support for shebangs was officially added in ts-node v8.9.0. The recommended shebang string now includes the -script suffix:

#!/usr/bin/env ts-node-script

Scripts using fs.readFileSync("somefile.json") are working for me with this shebang.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.