Reputation: 504
Basically, I am using Node's FS module to read and write to a JSON file. Writing it works completely fine but for some reason reading it returns an empty string.
This file is called 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
. However if that was the cause, writing a file wouldn't work either.
Directory
servers.json
src/
index.js
util/
records.js
Upvotes: 1
Views: 3833
Reputation: 111336
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.
In your case an absolute path to the file in your directory structure when accessed from records.js would be:
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. You can do it with 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.
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:
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.
As Robert pointed out in the comments, it should be noted that require()
or readFileSync()
(or anythingSync
) should only be used on the first tick of the event loop. 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, e.g. in request controllers, event handlers, async functions etc. then only fs.readFile()
or stream functions should be used.
Upvotes: 0
Reputation: 504
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.
Sorry for wasting your time.
Upvotes: 2