簡體   English   中英

錯誤:ENOENT:沒有這樣的文件或目錄,打開嘗試使用 fs 訪問目錄時

[英]Error: ENOENT: no such file or directory, open When trying to access a directory with fs

我對 nodejs 或 express 不了解,我有一個在 http://localhost:3000 上運行的 API,並且其中一個端點調用了一個使用文件系統同步讀取文件的函數。 當我在郵遞員上發出發布請求時,它在控制台中說它無法讀取不存在的路徑(據我了解)。

相關代碼:

index.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'

路徑: 來自 index.js 的 stateLogic.js 路徑,以及來自 stateLogic.js 的 root.txt 路徑

問題:

為什么它說路徑不存在? 我做錯了什么? 感謝您的時間。

您必須使用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值。

我們可以使用路徑模塊為目錄提供絕對路徑

folder
  |-server.js
  |-cert.pem

在 server.js 文件中

const const path = require('path') 
const certpath = path.join(__dirname,'chain.pem'); // folder\chain.pem

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM