简体   繁体   English

NodeJS readFileSync()返回一个空字符串

[英]NodeJS readFileSync() returns an empty String

Basically, I am using Node's FS module to read and write to a JSON file. 基本上,我使用Node的FS模块读取和写入JSON文件。 Writing it works completely fine but for some reason reading it returns an empty string. 编写它完全可以正常工作,但是由于某种原因读取它会返回一个空字符串。

This file is called records.js 该文件称为records.js。

const dir = 'servers.json';

function write(content) {
    fs.writeFileSync(dir, content);
}

function read() {
    return fs.readFileSync(dir, 'utf-8');
}

var file = read(); //This is always empty

One thing tho: That script is a seperate module and is located in a subfolder to my main index.js . 一件事:该脚本是一个单独的模块,位于我的主要index.js的子文件夹中。 However if that was the cause, writing a file wouldn't work either. 但是,如果这是原因,编写文件也将不起作用。

Directory 目录

servers.json
src/
    index.js
    util/
        records.js

Oh I am so dumb! 哦,我好笨! The code I posted didn't have any mistakes actually. 我发布的代码实际上没有任何错误。 One thing I didn't include was that I fired fs.open before I read the file and I didn't know fs.open wipes a file, I just thought it would create it in case it didn't exist. 有一件事我没有包括的是,我解雇fs.open之前,我阅读文件,我不知道fs.open湿巾一个文件,我只是想, 如果它不存在,将创建它。

Sorry for wasting your time. 很抱歉浪费您的时间。

First of all, every time that you read or write any file on the file system, always use an absolute path. 首先,每次您在文件系统上读取或写入任何文件时,请始终使用绝对路径。 When you use a relative path like you do here then it is relative to process.cwd() which may not be what you think. 当您像在此处那样使用相对路径时,则它相对于process.cwd()可能与您的想法无关。

In your case an absolute path to the file in your directory structure when accessed from records.js would be: 在您的情况下,从records.js访问目录结构中文件的绝对路径为:

let path = path.join(__dirname, '..', '..', 'servers.json');

or: 要么:

let path = path.join(__dirname, '../../servers.json');

And instead of just: 而不仅仅是:

var file = read();

you actually need to run: 您实际上需要运行:

write('something');

and then: 接着:

var file = read();

Also, since you're file to read seems to be JSON then you may want to read it as JSON. 另外,由于您要读取的文件似乎是JSON,因此您可能希望将其读取为JSON。 You can do it with require: 您可以使用require来做到这一点:

let object = require('../../file.json');

or you can read it and then parse it as JSON with JSON.parse() - but in that case make sure to put it inside of try / catch or otherwise your program will crash on invalid JSON. 或者您可以读取它,然后使用JSON.parse()将其解析为JSON.parse()但在这种情况下,请确保将其放入try / catch ,否则您的程序将在无效的JSON上崩溃。

Another thing is that since you said that it is a module that is required somewhere else, make sure to actually export the value that you want to be used somewhere else. 另一件事是,由于您说这是其他地方需要的模块,因此请确保确实导出要在其他地方使用的值。 For example: 例如:

var file = read();
module.exports = file;

and where you use it: 以及使用位置:

var data = require('records.js');

But note that when you have a JSON file then you can require it in other modules directly like this: 但是请注意,当您拥有JSON文件时,可以直接在其他模块中要求它,如下所示:

var data = require('../../servers.json');

with no need of having a module which has only one purpose of reading the JSON and exporting it to other modules. 不需要一个仅具有读取JSON并将其导出到其他模块的目的的模块。

Update 更新

As Robert pointed out in the comments, it should be noted that require() or readFileSync() (or anything Sync ) should only be used on the first tick of the event loop. 正如Robert在评论中指出的那样,应该注意的是, require()readFileSync() (或anything Sync )仅应在事件循环的第一时间使用。 I assumed that here the file is read once on startup and the results get exported for use by requiring modules. 我假设这里文件在启动时被读取一次,结果被导出以供需要的模块使用。 If the file is read during the lifetime of the program, eg in request controllers, event handlers, async functions etc. then only fs.readFile() or stream functions should be used. 如果在程序生存期内(例如,在请求控制器,事件处理程序,异步函数等中fs.readFile()读取文件,则仅应使用fs.readFile()或流函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM