M
M
Moro Zota2018-03-24 00:05:52
JavaScript
Moro Zota, 2018-03-24 00:05:52

How to specify file path through fs module?

var fs = require('fs')

fs.readFile(????, function (err, data){
  console.info(data.toString())
})

How to correctly specify the path to the file in the first argument?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Eugene, 2018-03-24
@3Lvcz

As a rule, by merging the path to the directory in which the given file __dirname is located and the relative path to the file relative to it.

my_project/
├── assets/
│   └── somefile.txt
├── src/
│   └── script.js
└── package.json

// script.js

var fs = require('fs'); 
var path = require('path');

var filePath = path.join(__dirname, '../assets/somefile.txt');

fs.readFile(filePath, function (err, data) {
  console.log.info(data.toString());
});

E
eternalSt, 2018-03-24
@eternalSt

At first I wanted to write a large detailed answer, but in the process I realized that I was rewriting offs. docks.
Therefore, I decided to give a few links yes off. docks. It's all laid out pretty well.
Read the doc about the file system (fs module) , the sections directly related to the question ( File paths , URL object support , File Descriptors )
And in addition to Eugene 's answer, read the doc about the path ( join , normalize are directly related to the question ) and __dirname
PS Read off. docks. Many questions will disappear immediately. If you don't understand English. Use the translator and experiment with the code. A few days and you will be easy to navigate in the docks, and you will get to know the node better. By the way, there is an excellent site where many different docks are collected. devdocs.io

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question