Reputation: 8706
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.
Upvotes: 5
Views: 6365
Reputation: 9825
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.
Upvotes: 1
Reputation: 10377
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.
Upvotes: 6