我不了解 nodejs 或 express,我在 http://localhost:3000 上運行了一個 API,其中一個端點呼叫了一個使用檔案系統同步讀取檔案的函式。當我對郵遞員發出帖子請求時,它在控制臺中說它無法讀取不存在的路徑(這對我的理解是這樣)。
相關代碼:
索引.js
app.post('/write',(req,res)=>
{
var body = req.body;
console.log('endpoint reached');
console.log(body);
logic.append(body.key,body.path);
res.send('Writting to state was successful');
});
stateLogic.js(這發生在 trieRoot 的第一次初始化時)
async append(key,path)
{
var trieRoot = Buffer.from(programData.volatile.modularVariables.readSync(programData.persistent.paths.srcRoot,programData.volatile.modularVariables.encoding.utf8),'hex');
console.log(trieRoot);
var db = programData.persistent.states.singularity;
var trie = new merkle_patricia_tree_1.SecureTrie(db,trieRoot);
var data = programData.volatile.modularVariables.readSync(path,programData.volatile.modularVariables.encoding.utf8);
var format = programData.volatile.modularVariables.getFormat(path);
var name = programData.volatile.modularVariables.getName(path);
var inData = JSON.stringify({name,format,data});
console.log(`key: ${key} value: ${inData}`);
await trie.put(Buffer.from(key),Buffer.from(inData));
var root = await trie.root;
programData.volatile.modularVariables.write(programData.persistent.paths.srcRoot,root.toString('hex'),programData.volatile.modularVariables.writeCB);
var retGet = await trie.get(Buffer.from(key));
console.log('Get returned:' retGet.toString());
console.log(`From Stack: ${root.toString('hex')} From File: ${this.malleableVar}`);
return;
};
使用的 readSync 函式:
readSync: (file,encoding)=>{return fs.readFileSync(file,{encoding:encoding,flag:'r'})},
使用的 srcRoot 值:
srcRoot: './storage/root.txt'
控制臺錯誤:
(node:18808) UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, open './storage/root.txt'
路徑:

問題:
為什么它說路徑不存在時呢?我做錯了什么?感謝您的時間。
uj5u.com熱心網友回復:
你必須使用absolute path而不是relative path
index.js使用以下代碼修改您的:
const path = require('path') // <-- import path module to use absolute path.
app.post('/write',(req,res)=>
{
var body = req.body;
const absPath = path.join(__dirname, body.path); // <-- absolute path
console.log("Absolute Path: ", absPath);
logic.append(body.key, absPath);
res.send('Writting to state was successful');
});
注意:如果您仍然面臨相同的錯誤,請檢查body.path值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/333149.html
標籤:javascript 节点.js 表达 服务器 目录
