Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read and write a text file in typescript

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.

like image 345
william007 Avatar asked Nov 11 '15 02:11

william007


People also ask

How do I read a text file in TypeScript?

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.

How do you create a text file in TypeScript?

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!

What is the difference between readFile and readFileSync?

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.

How do I run a script in TypeScript?

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.


1 Answers

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

More

Node quick start : https://basarat.gitbooks.io/typescript/content/docs/node/nodejs.html

like image 176
basarat Avatar answered Sep 22 '22 09:09

basarat