How should I read and write a text file from typescript in node.js? I am not sure would read/write a file be sandboxed in node.js, if not, i believe there should be a way in accessing file system.
Use the readFileSync() method to read a file's contents in TypeScript, e.g. readFileSync(join(__dirname, 'example. txt'), 'utf-8') . The method takes the path and encoding as parameters and returns the contents of the specified file.
Use the fs. writeFileSync() method to write to a file in TypeScript, e.g. writeFileSync(join(__dirname, filename), data) . The method takes the path to the file, the data and an options object as parameters and writes the provided content to the file. Copied!
In fs. readFile() method, we can read a file in a non-blocking asynchronous way, but in fs. readFileSync() method, we can read files in a synchronous way, i.e. we are telling node. js to block other parallel process and do the current file reading process.
We can use the ts-node package to execute TypeScript files from the command line. Install it with npm or other package manager. After that, simply execute the TypeScript files with the command: ts-node filename.
believe there should be a way in accessing file system.
Include node.d.ts
using npm i @types/node
. And then create a new tsconfig.json
file (npx tsc --init
) and create a .ts
file as followed:
import * as fs from 'fs'; fs.readFileSync('foo.txt','utf8');
You can use other functions in fs
as well : https://nodejs.org/api/fs.html
Node quick start : https://basarat.gitbooks.io/typescript/content/docs/node/nodejs.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With