How to properly write json file only if the file doesn't exist.
fs.exists
method is deprecated so I won't use that.
Any idea?
How to properly write json file only if the file doesn't exist.
fs.exists
method is deprecated so I won't use that.
Any idea?
You just need to pass the 'wx'
flags to fs.writeFile()
. This will create and write the file if it does not exist or will return an error if the file already exists. This is supposed to be free of race conditions which fs.exist()
and fs.access()
are subject to because they don't have the ability to test and create the file in an atomic action that cannot be interrupted by any other process.
Here's an encapsulated version of that concept:
// define version of fs.writeFile() that will only write the file
// if the file does not already exist and will do so without
// possibility of race conditions (e.g. atomically)
fs.writeFileIfNotExist = function(fname, contents, options, callback) {
if (typeof options === "function") {
// it appears that it was called without the options argument
callback = options;
options = {};
}
options = options || {};
// force wx flag so file will be created only if it does not already exist
options.flag = 'wx';
fs.writeFile(fname, contents, options, function(err) {
var existed = false;
if (err && err.code === 'EEXIST') {
// This just means the file already existed. We
// will not treat that as an error, so kill the error code
err = null;
existed = true;
}
if (typeof callback === "function") {
callback(err, existed);
}
});
}
// sample usage
fs.writeFileIfNotExist("myFile.json", someJSON, function(err, existed) {
if (err) {
// error here
} else {
// data was written or file already existed
// existed flag tells you which case it was
}
});
See a description of the flag values you can pass to fs.writeFile()
here in the node.js doc.
FS
const fs = require('fs');
import fs from 'fs';
if (!fs.existsSync('db.json')) fs.writeFileSync(JSON.stringify({
'hey-there': 'Hello World!',
peace: 'love'
}));
const jsonFile = 'db.json';
const defaultJsonData = JSON.stringify({
'hey-there': 'Hello World!',
peace: 'love'
});
if (!fs.existsSync(jsonFile)) fs.writeFileSync(defaultJsonData);
const jsonFile = 'db.json';
const defaultJsonData = {
'hey-there': 'Hello World!',
peace: 'love'
};
if (!fs.existsSync(jsonFile)) fs.writeFileSync(JSON.stringify(defaultJsonData));
const jsonFile = 'db.json';
let jsonData = {};
if (fs.existsSync(jsonFile)) {
jsonData = JSON.parse(fs.readFileSync(jsonFile));
} else {
jsonData = {
'hey-there': 'Hello World!',
peace: 'love'
}
fs.writeFileSync(JSON.stringify(jsonData));
}
if the file db.json exist read the string from that file and parse it, else set the json default data and stringify it into the db.json file..
console.log(jsonData['hey-there']); // Hello World!
console.log(jsonData.peace); // love
function createJsonFile(fileName) {
if (!fs.existsSync(fileName)) fs.writeFileSync(JSON.stringify({
'hey-there': 'Hello World!',
peace: 'love'
})); // optionally wrap that in try,catch block and return false inside the catch
return true;
}
const defaultJsonData = JSON.stringify({
'hey-there': 'Hello World!',
peace: 'love'
});
function createJsonFile(fileName) {
if (!fs.existsSync(jsonFile)) fs.writeFileSync(defaultJsonData); // optionally wrap that in try,catch block and return false inside the catch
return true;
}
const defaultJsonData = {
'hey-there': 'Hello World!',
peace: 'love'
};
function createJsonFile(fileName) {
if (!fs.existsSync(jsonFile)) fs.writeFileSync(JSON.stringify(defaultJsonData)); // optionally wrap that in try,catch block and return false inside the catch
return true;
}
createJsonFile('db.json');
// or if you wrapped the function content in try,catch block and returned false inside the catch
const jsonFile = 'db.json';
if (createJsonFile(jsonFile)) {
console.log(`Created ${jsonFile}`);
} else {
console.log(`Failed Creating ${jsonFile}`);
}
function createJsonFile(fileName) {
try {
if (!fs.existsSync(fileName)) fs.writeFileSync(JSON.stringify({
'hey-there': 'Hello World!',
peace: 'love'
}));
} catch(e) {
return false;
}
return true;
}
function createJsonFile(fileName) {
if (fs.existsSync(jsonFile)) return JSON.parse(fs.readFileSync(jsonFile));
// else.. (return ^_^)
const defaultJsonData = {
'hey-there': 'Hello World!',
peace: 'love'
}
fs.writeFileSync(JSON.stringify(defaultJsonData));
return defaultJsonData;
}
const jsonFile = 'db.json';
const jsonData = createJsonFile(jsonFile);
console.log(jsonData['hey-there']); // Hello World!
console.log(jsonData.peace); // love
module.exports = {
createJsonFile
}
const { createJsonFile } = require('./file-in-same-dir.js'); // you don't have to specify .js
export default {
createJsonFile
};
import whatEverVariableName from './file-in-same-dir.js'; // you don't have to specify .js
whatEverVariableName.createJsonFile('db.json');
// example for variable names I use: db, api, tools
// db.js
import DB from './db';