I need help with this error:
Error occured while storing data to file SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at storeDataToFile (C:\Users\alaiy\Documents\NFTs\nft-demo-master\scripts\ipfsHelper.js:19:23)
at async pinFileToIPFS (C:\Users\alaiy\Documents\NFTs\nft-demo-master\scripts\pinFileToIPFS.js:29:5)
Successfully added IPFS response to json file
I'm using the following scripts to upload an image to a IPFS site (Pinata) and then add the IPFS hash to either new/existing json file. Any help is appreciated!
I've got my dev.json file which basically says to add the hash to the ipfsHash.json file. If not then create one and add:
{
"ipfsFile": {
"location": "../data/ipfsHash.json"
}
}
I've got my runScript.js file which basically calls the pinFiletoIPFS file below:
const path = require('path');
const pinFileToIPFS = require('./pinFileToIPFS');
const filePath = path.join(__dirname, '../assets/homer.jpg');
// const filePath = path.join(__dirname, '../data/metadata.json');
pinFileToIPFS(filePath);
This is the script that is having issues. I have the ipfsHelp.js file which should add the data to my json file:
const fs = require('fs').promises;
const path = require('path');
const config = require('config');
// https://stackoverflow.com/questions/36856232/write-add-data-in-json-file-using-node-js
// Accepts json data and stores in specified filePath.
// If the file does not exists in specified location, it creates it
const storeDataToFile = async (jsonData) => {
try {
const filePath = path.join(__dirname, config.get('ipfsFile.location'));
const ipfsFileExists = await fileExists(filePath);
if (!ipfsFileExists) {
console.log('ipfsFileExists: ', ipfsFileExists);
// First time creating an empty file with [].
// We will be storing all ipfsHashes as array of objects
await fs.writeFile(filePath, JSON.stringify([]));
}
const data = await fs.readFile(filePath, 'utf8');
const json = JSON.parse(data);
json.push(jsonData);
await fs.writeFile(filePath, JSON.stringify(json));
} catch (err) {
console.log('Error occured while storing data to file', err);
}
};
async function fileExists(path) {
try {
const res = await fs.access(path);
return true;
} catch (err) {
// no such file or directory. File really does not exist
if (err.code == 'ENOENT') {
return false;
}
console.log('Exception fs.statSync (' + path + '): ' + err);
// some other exception occurred
throw err;
}
}
module.exports = {
storeDataToFile,
fileExists,
};
I've used this module: https://www.npmjs.com/package/config
I have a config folder in my root folder where the json file is inside.
Not sure what i'm doing wrong.
EDITTT:
I FOUND THE SOLUTIO thanks to Why is process.env.NODE_ENV undefined?
The code was not working all because I have to type the following in cmd which sets the variable in the environment!! :
SET NODE_ENV=dev