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.
8 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.gitbook.io/typescript/nodejs

- 261,912
- 58
- 460
- 511
-
6With your code I get error TS2307: Cannot find module 'fs'. Node v.6.4.0 and tsc v.1.8.10. Do you have any advice? – WorkingMatt Aug 31 '16 at 20:34
-
11@WorkingMatt `npm install --save-dev @types/node` – TecHunter May 09 '17 at 09:27
-
3how comes we use require here and not import? – K-Dawg Apr 01 '19 at 14:40
-
4@PrimeByDesign just a really really old answer. Updated for latest tech – basarat Apr 02 '19 at 05:15
-
@basarat ah thank you! I thought there might be a specific reason. – K-Dawg Apr 07 '19 at 20:45
-
11using ES6 syntax it will be `import * as fs from 'fs';` – notracs Dec 08 '19 at 14:44
-
1Where is foo.txt located?, if I put foo.txt in same directory as .ts file, foo.txt cannot be found I ended up using this: const file = fs.readFileSync(path.join(__dirname, 'foo.txt'), 'utf8'); where path object is imported using: import * as path from 'path'; – Wadi Diaz-wong Apr 21 '21 at 22:37
-
fs.writeFileSync is not a function – Roberto Pegoraro Jan 19 '22 at 22:06
-
I get `Uncaught TypeError: fs__WEBPACK_IMPORTED_MODULE_1__.readFileSync is not a function` – Black Jun 10 '22 at 06:53
import { readFileSync } from 'fs';
const file = readFileSync('./filename.txt', 'utf-8');
This worked for me.
You may need to wrap the second command in any function or you may need to declare inside a class without keyword const
.

- 279
- 3
- 3
First you will need to install node definitions for Typescript. You can find the definitions file here:
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/node/node.d.ts
Once you've got file, just add the reference to your .ts
file like this:
/// <reference path="path/to/node.d.ts" />
Then you can code your typescript class that read/writes, using the Node File System module. Your typescript class myClass.ts
can look like this:
/// <reference path="path/to/node.d.ts" />
class MyClass {
// Here we import the File System module of node
private fs = require('fs');
constructor() { }
createFile() {
this.fs.writeFile('file.txt', 'I am cool!', function(err) {
if (err) {
return console.error(err);
}
console.log("File created!");
});
}
showFile() {
this.fs.readFile('file.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
}
}
// Usage
// var obj = new MyClass();
// obj.createFile();
// obj.showFile();
Once you transpile your .ts
file to a javascript (check out here if you don't know how to do it), you can run your javascript file with node and let the magic work:
> node myClass.js

- 185
- 1
- 3
import * as fs from 'fs';
import * as path from 'path';
fs.readFile(path.join(__dirname, "filename.txt"), (err, data) => {
if (err) throw err;
console.log(data);
})
EDIT:
consider the project structure:
../readfile/
├── filename.txt
└── src
├── index.js
└── index.ts
consider the index.ts
:
import * as fs from 'fs';
import * as path from 'path';
function lookFilesInDirectory(path_directory) {
fs.stat(path_directory, (err, stat) => {
if (!err) {
if (stat.isDirectory()) {
console.log(path_directory)
fs.readdirSync(path_directory).forEach(file => {
console.log(`\t${file}`);
});
console.log();
}
}
});
}
let path_view = './';
lookFilesInDirectory(path_view);
lookFilesInDirectory(path.join(__dirname, path_view));
if you have in the readfile folder and run tsc src/index.ts && node src/index.js
, the output will be:
./
filename.txt
src
/home/andrei/scripts/readfile/src/
index.js
index.ts
that is, it depends on where you run the node.
the __dirname is directory name of the current module.

- 346
- 3
- 9
-
This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/low-quality-posts/22758091) – Daij-Djan Apr 15 '19 at 15:50
-
2@Daij-Djan I don't think so. I do agree that the answer would be better with a few comments, but really, it's a minimal yet complete answer. – Nino Filiu Apr 15 '19 at 16:04
I encounter "Cannot find module 'fs' or its corresponding type declarations" when
import { readFileSync } from 'fs';
How I solve it
A bit deviation from Jerome Villiseck's ans
Edit tsconfig.app.json:
...
"include": [
"src/**/*.d.ts",
"node_modules/@types/node/"
]
...

- 19
- 2
Just to clarify: if ever the TS 2307: Cannot find module import error appears: check the tsconfig.json file.
It must contain node_modules
{
.....
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"tests/**/*.ts",
"tests/**/*.tsx",
"node_modules"
],
.....
}

- 1
- 3
It is possible to write file in ts. But something how its js. You can install jquery to run javascript in angular.
npm i jquery
Import in it in angular.json file and use this code
var fileWriter = new Writer();
var fileName = "test_syskey/Test.doc";
fileWriter.removeFile(fileName, function(err,url) {
if (err) {
resp.error("Write failed");
} else {
resp.success(url);
}
});

- 1
- 2
I was receiving the Cannot find module 'fs' or its corresponding type declarations
error, even with @types/node installed. Here is the full solution that worked for me:
In terminal:
npm install --save-dev @types/node
In the script (src/fileReader.ts
):
/// <reference path="../node_modules/@types/node/fs.d.ts" />
import fs from "fs";
let data = fs.readFileSync("myfile.txt")
Version list:
npm version: 9.3.1
node version: 19.5.0
@types/node version: 18.15.0
tsc version: 4.7.4

- 152
- 1
- 11