【问题标题】:Error: ENOENT: no such file or directory, open When trying to access a directory with fs错误:ENOENT:没有这样的文件或目录,打开尝试使用 fs 访问目录时
【发布时间】:2021-12-09 22:17:38
【问题描述】:

我不熟悉 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'

路径:

问题:

为什么它说路径不存在?我做错了什么?感谢您的宝贵时间。

【问题讨论】:

    标签: javascript node.js express server directory


    【解决方案1】:

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

    【讨论】:

    • 这可能是未来的问题,但这不是上面的错误。但是,我会尝试将 srcRoot 作为绝对路径
    猜你喜欢
    • 1970-01-01
    • 2021-10-11
    • 2018-07-06
    • 1970-01-01
    • 2019-01-26
    • 2021-06-08
    • 2019-06-24
    • 2016-07-05
    • 2013-02-04
    相关资源
    最近更新 更多