Arc
Arc

Reputation: 103

readFile in nodejs with Typescript

I start to learn typescript today, and there's a problem.

Here is the filetree(after compiling):

dist
    index.js
src
    data.txt
    index.ts

Here is ./src/index.ts:

import { readFileSync } from 'fs';

let data = readFileSync('./data.txt');
console.log(data);

After compiling with command "tsc", it creates ./dist/index.js, absolutely the file data.txt cannot be read correctly. How to make it the right path?

Upvotes: 2

Views: 13004

Answers (1)

zhangjinzhou
zhangjinzhou

Reputation: 2701

Usually you are not supposed to put data in src folder. There are several ways if you really want to do so:

  1. copy data.txt to dist while compiling typescript
  2. use absolute path which could be path.join(__dirname, "../src/data.txt")
  3. Since you already know index.ts is going to be compiled to dist, use "../src/data.txt" directly

Upvotes: 4

Related Questions