I am not knowledgeable in nodejs or express, I have an API running on http://localhost:3000 and one of the endpoints call a function that uses file system to read file synchronously. When I make a post request on postman, it says in the console that it can’t read a path that doesn’t exist (which does to my understanding).
Relevant code:
index.js
JavaScript
x
9
1
app.post('/write',(req,res)=>
2
{
3
var body = req.body;
4
console.log('endpoint reached');
5
console.log(body);
6
logic.append(body.key,body.path);
7
res.send('Writting to state was successful');
8
});
9
stateLogic.js (this occurs on first initialization of trieRoot)
JavaScript
1
34
34
1
async append(key,path)
2
{
3
var trieRoot = Buffer.from(programData.volatile.modularVariables.readSync(programData.persistent.paths.srcRoot,programData.volatile.modularVariables.encoding.utf8),'hex');
4
5
console.log(trieRoot);
6
7
var db = programData.persistent.states.singularity;
8
var trie = new merkle_patricia_tree_1.SecureTrie(db,trieRoot);
9
10
var data = programData.volatile.modularVariables.readSync(path,programData.volatile.modularVariables.encoding.utf8);
11
12
var format = programData.volatile.modularVariables.getFormat(path);
13
14
var name = programData.volatile.modularVariables.getName(path);
15
16
var inData = JSON.stringify({name,format,data});
17
18
19
console.log(`key: ${key} value: ${inData}`);
20
21
await trie.put(Buffer.from(key),Buffer.from(inData));
22
23
var root = await trie.root;
24
25
programData.volatile.modularVariables.write(programData.persistent.paths.srcRoot,root.toString('hex'),programData.volatile.modularVariables.writeCB);
26
27
var retGet = await trie.get(Buffer.from(key));
28
29
console.log('Get returned:'+retGet.toString());
30
console.log(`From Stack: ${root.toString('hex')} From File: ${this.malleableVar}`);
31
32
return;
33
};
34
readSync function used:
JavaScript
1
2
1
readSync: (file,encoding)=>{return fs.readFileSync(file,{encoding:encoding,flag:'r'})},
2
srcRoot value used:
JavaScript
1
2
1
srcRoot: './storage/root.txt'
2
Console Error:
JavaScript
1
2
1
(node:18808) UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, open './storage/root.txt'
2
Questions:
Why does it say the path doesn’t exist when it does? And what is it I am doing wrong? Thank you for your time.
Advertisement
Answer
You’ve to use absolute path
instead of relative path
Modify your index.js
with the below code:
JavaScript
1
11
11
1
const path = require('path') // <-- import path module to use absolute path.
2
3
app.post('/write',(req,res)=>
4
{
5
var body = req.body;
6
const absPath = path.join(__dirname, body.path); // <-- absolute path
7
console.log("Absolute Path: ", absPath);
8
logic.append(body.key, absPath);
9
res.send('Writting to state was successful');
10
});
11
Note: If you’re still facing the same error, then check body.path
value.