Reading and writing a text file in typescript

How do I read and write a text file from typescript in node.js? I'm not sure if reading / writing the file will be isolated in node.js, if not, I believe there should be a way to access the file system.

+15
source share
4 answers

  I believe that there should be a way to access the file system.

Turn on node.d.tsusing npm i @types/node. Then create a new file tsconfig.json( npx tsc --init) and create the file .tsas follows:

import fs from 'fs';
fs.readFileSync('foo.txt','utf8');

You can also use other functions in fs: https://nodejs.org/api/fs.html

More

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

+26

Typescript. :

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/node/node.d.ts

, .ts :

/// <reference path="path/to/node.d.ts" />

/, Node File System. myClass.ts :

/// <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();

.ts javascript ( , , ), javascript :

> node myClass.js
+6
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);
})

:

:

../readfile/
├── filename.txt
└── src
    ├── index.js
    └── index.ts

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

readfile tsc src/index.ts && node src/index.js, :

./
        filename.txt
        src

/home/andrei/scripts/readfile/src/
        index.js
        index.ts

, .

__dirname .

+2
import { readFileSync } from 'fs';

const file = readFileSync('./filename.txt', 'utf-8');

. , const.

+1

Source: https://habr.com/ru/post/1615340/


All Articles