[node.js] 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.

This question is related to node.js typescript

The answer is


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 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


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.


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

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.


Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to typescript

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type?