为什么我使用Node核心模块'fs'获得了NOENT

时间:2018-11-20 18:01:20

标签: node.js json fs

这是一个重复的问题(尚未回答),但是我已经修改并收紧了代码。而且,我已经包括了具体示例。很抱歉继续打这鼓,但是我需要帮助。

这是一个Node API。我需要读写JSON数据。我正在使用节点核心模块'fs',而不是同名的npm软件包(或fs-extra)。我已经将关注的特定区域提取到一个独立模块上,如下所示:

'use strict';

/*==================================================
    This service GETs the list of ids to the json data files 
    to be processed, from a json file with the id 'ids.json'.
    It returns and exports idsList (an array holding the ids of the json data files)
    It also calls putIdsCleared to clear the 'ids.json' file for the next batch of processing
==================================================*/

//  node modules
const fs          = require('fs');
const config      = require('config');

const scheme      = config.get('json.scheme')
const jsonPath    = config.get('json.path');
const url         = `${scheme}${jsonPath}/`;
const idsID       = 'ids.json';
const uri         = `${url}${idsID}`;
let idsList = [];

const getList = async (uri) => {
    await fs.readFile(uri, 'utf8', (err, data) => {
        if (err) {
            return(console.log( new Error(err.message) ));
        }
        return jsonData = JSON.parse(data);
    })
}

//  The idea is to get the empty array written back to 'ids.json' before returning to 'process.js'
const clearList = async (uri) => {
    let data = JSON.stringify({'ids': []});
    await fs.writeFile(uri, data, (err) => {
        if (err) {
            return (console.log( new Error(err.message) ));
        }
        return;
    })
}

getList(uri);

clearList(uri)

console.log('end of idsList',idsList);

module.exports = idsList;

这是模块执行的控制台输出:

    Error: ENOENT: no such file or directory, open 'File:///Users/doug5solas/sandbox/libertyMutual/server/api/ids.json'
        at ReadFileContext.fs.readFile [as callback] 

 (/Users/doug5solas/sandbox/libertyMutual/server/.playground/ids.js:24:33)
        at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:235:13)
    Error: ENOENT: no such file or directory, open 'File:///Users/doug5solas/sandbox/libertyMutual/server/api/ids.json'
        at fs.writeFile 

 (/Users/doug5solas/sandbox/libertyMutual/server/.playground/ids.js:36:34)
        at fs.js:1167:7
        at FSReqWrap.oncomplete (fs.js:141:20)

有人告诉我没有这样的文件或目录。但是我可以复制uri(如错误消息中所示)

File:///Users/doug5solas/sandbox/libertyMutual/server/api/ids.json

进入浏览器的搜索栏,这就是返回给我的信息:

{
    "ids": [
        "5sM5YLnnNMN_1540338527220.json",
        "5sM5YLnnNMN_1540389571029.json",
        "6tN6ZMooONO_1540389269289.json"
    ]
}

此结果是预期结果。我没有“理解”为什么可以手动获取数据,但是无法使用相同的uri以编程方式获取数据。我想念什么?帮助表示赞赏。

2 个答案:

答案 0 :(得分:0)

您的文件URI格式错误。 它不应包含File://协议(这是特定于浏览器的内容)。

我想你想要C://Users/doug5solas/sandbox/libertyMutual/server/api/ids.json

答案 1 :(得分:0)

我通过进入readFileSync解决了这个问题。我不喜欢它,但是它可以工作,而且只有一读。