javascript - readFile in nodejs with Typescript - Stack Overflow

I start to learn typescript today, and there's a problem.Here is the filetree(after piling):dist

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

Here is the filetree(after piling):

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 piling with mand "tsc", it creates ./dist/index.js, absolutely the file data.txt cannot be read correctly. How to make it the right path?

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

Here is the filetree(after piling):

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 piling with mand "tsc", it creates ./dist/index.js, absolutely the file data.txt cannot be read correctly. How to make it the right path?

Share Improve this question asked Jul 5, 2018 at 17:06 ArcArc 1031 gold badge2 silver badges8 bronze badges 7
  • You can pile the files to same folder. don't pass any "outDir": "DIRECTORY" in the piler options. – Kiba Commented Jul 5, 2018 at 17:10
  • data.txt shouldn't be in src, its a resource as in it's only used by the piled code, so move it to dist (because you want to distribute that file with your code) and your problem will be solved. . – Adam H Commented Jul 5, 2018 at 17:15
  • Or you create a 3rd folder like res, move the file there, then use ../res/data.txt and it'll always work. – user5734311 Commented Jul 5, 2018 at 17:21
  • @ChrisG That is good advice, i just didn't want to confuse the poor guy with yet another folder. – Adam H Commented Jul 5, 2018 at 17:23
  • @ChrisG But as final production, we only take out the "dist" folder, right? A 3rd folder will be so redundant. Is there any tool that can move 'data.txt' to dist and keep the path correct just like vue-cli and webpack? – Arc Commented Jul 5, 2018 at 17:42
 |  Show 2 more ments

1 Answer 1

Reset to default 4

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 piling 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 piled to dist, use "../src/data.txt" directly

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744223223a4563883.html

相关推荐

  • javascript - readFile in nodejs with Typescript - Stack Overflow

    I start to learn typescript today, and there's a problem.Here is the filetree(after piling):dist

    8天前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信