I'm building a static blog using Nextjs 13 and deploying it on Vercel. I builded and started the project locally and everything was working, but on Vercel I got this error:
ERROR Error: ENOENT: no such file or directory, open 'posts/second.md' at Object.openSync (node:fs:600:3) at Object.readFileSync (node:fs:468:35) at getPostBySlug (/var/task/.next/server/chunks/207.js:146:63) at Post (/var/task/.next/server/app/posts/[slug]/page.js:603:52) at T (/var/task/.next/server/chunks/760.js:11441:25) at Ma (/var/task/.next/server/chunks/760.js:11604:33) at Array.toJSON (/var/task/.next/server/chunks/760.js:11397:32) at stringify () at V (/var/task/.next/server/chunks/760.js:11696:53) at ping (/var/task/.next/server/chunks/760.js:11496:43) { errno: -2, syscall: 'open', code: 'ENOENT', path: 'posts/second.md'}
The error happens when I go to the "/posts/second" route for example, not in the main page
This is the code interested:
const getPostBySlug = (slug: string) => {
const folder = "posts/";
const file = `${folder}${slug}.md`;
const content = fs.readFileSync(file, "utf8");
return matter(content)
};
The posts folder is located in the root folder.
I tried to modify the next config by adding the output option and setting it to 'standalone':
const nextConfig = {
// config
output: 'standalone',
}
I also tried to modify the path to locate the folder but nothing seems to work.
If more information is needed. project is published on GitHub
I solved my problem by looking at a tutorial provided by Vercel, so thanks to this line of code path.join(process.cwd(), 'posts'); the folder path is resolved.
Related
I have a simple NextJS API page which just fetches a JSON file from one of the node_modules and shows the content at http://localhost:3000/api/my-json. This is the code:
// Path: /pages/api/my-json.ts
import type { NextApiRequest, NextApiResponse } from "next";
import path from "path";
import { promises as fs } from "fs";
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
//Find the absolute path of the json directory
const jsonLocation = path.join(
process.cwd(),
"node_modules/#my-company/my-package/lib/my-json-file.json"
);
//Read the json data file data.json
const fileContents = await fs.readFile(jsonLocation, "utf8");
//Return the content of the data file in json format
res.status(200).json(fileContents);
}
It works fine in dev mode, also works when building a production NextJS app by running:
yarn install
yarn build
yarn start
But when I upload the code to Vercel, the app is unable to find the json file, and my page https://my-app.vercel.app/api/my-json returns 500 error:
2022-12-12T10:25:14.142Z 04b6a8fe-53f7-46b6-8c49-98dadf358eb3 ERROR [Error: ENOENT: no such file or directory, open '/var/task/node_modules/#my-company/my-package/lib/my-json-file.json'] {
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: '/var/task/node_modules/#my-company/my-package/lib/my-json-file.json'
}
Somebody had this problem before? Do I need to copy that JSON file manually somehow during Vercel deployment? How comes it works on local builds but not on Vercel?
I was requiring some data from a .json file but I am getting this error:
Error: ENOENT: no such file or directory, open '../Jsons/eshop.json'
at Object.openSync (node:fs:585:3)
at Object.readFileSync (node:fs:453:35)
at Object.execute (C:\Users\Pooyan\Desktop\PDM Bot Main\commands\shop.js:9:24)
at module.exports (C:\Users\Pooyan\Desktop\PDM Bot Main\events\guild\message.js:114:15)
errno: -4058,
syscall: 'open',
code: 'ENOENT',
path: '../Jsons/eshop.json'
}
My code:
let shop_data = JSON.parse(Buffer.from(fs.readFileSync('../Jsons/eshop.json')).toString());
let index = (args[0] || "1");
let page = shop_data.pages[index];
I think that's all you need, but if any other code was needed, comment it.
I am using discord.js v13 and node.js 16
The issue is with the path. It seems the path is invalid for the given eshop.json file or there might be any spelling mistake in the path.
fs.readFileSync takes the relative path:
test.js
JSON
sampleJSON
eshop.json
fs.readFileSync('./JSON/sampleJSON/eshop.json');
You need to use path module and join the folder names to define the json file location.
Let,the data is in following directory. ( NewProject/data/eshop.json )
NewProject
Project root directory
data
eshop.json
You want to access the eshop.json file from any file under the project directory.
Solution is below:
const fs = require('fs')
const path = require('path');
const directory = path.join('data', 'eshop.json')
// directory ==> data\eshop.json
exports.getRandomUserService = () => {
const jsonData = fs.readFileSync(directory);
const eshop= JSON.parse(jsonData);
console.log('eshop data from json file: ',eshop);
}
Please help me to solve..
My JS file file is in Next JS app > pages/api/profile and google-cloud-key.json is in Next JS app root folder itself where package.json is there.
Everything works fine in local, but below error given at Vercel
ENOENT: no such file or directory, open '/var/task/google-cloud-key.json' vercel
My google-cloud-key.json is in the root directory of next JS app.
I have tried below code also:
const storage = new Storage({
projectId: 'careful-relic-319511',
keyFilename: __dirname + '/../../../google-cloud-key.json'
});
This is giving below error now:
ENOENT: no such file or directory, open '/var/task/.next/server/google-cloud-key.json'] {\n errno: -2,\n code: 'ENOENT',\n syscall: 'open',\n path: '/var/task/.next/server/google-cloud-key.json'\n}\nEND
Hey i found a great solution
Base64 encode the json file. (https://www.base64encode.org/)
Set an env variable (both in local and vercel setting) this encoded string. (In my case GCP_CRED_FILE)
const gcsKey = JSON.parse(
Buffer.from(process.env.GCP_CRED_FILE, 'base64').toString()
);
const storage = new Storage({
credentials: {
client_email: gcsKey.client_email,
private_key: gcsKey.private_key
},
projectId: gcsKey.project_id
});
this works for me. tested using nextjs 11 and vercel deployments
Moreover you dont need to store or push the file to a repo or store it (which can be a security threat)
I've node program which should run and during runtime read some hidden file
.env.json or env.json. (not hidden file)
I've tried to print the following in the program which needs to read it:
dirname: /Users/i012344/projects/rs/deploy
fileName: /Users/i012344/projects/rs/deploy/deploy/index.js
process.argv[1]: /Users/i012344/.nvm/versions/node/v11.15.0/bin/yo
My running program called is: deploy/index.js
But I dont need this path as this print the location of the current executable program, I need to read a file from the current folder that I run
my program.
e.g.
/Users/i012344/projects/app1/.env.json
Now I run my program inside the app1 folder and needs to get the content of the .env.json file, how can I do it?
when I print
console.log("process.cwd(): ", process.cwd());
I got "/Users/i012344/projects"
I want: /Users/i012344/projects/app1
when running
let filePath = path.join(__dirname, ".env.json");
console.log("ft: ",filePath);
I got error as it search for it in the wrong place
fs.readFile(filePath, {encoding: "utf-8"}, function (err, data) {
if (!err) {
console.log("received data: " + data);
} else {
console.log(err);
}
});
{ [Error: ENOENT: no such file or directory, open 'Users/i012344/projects/rs/deploy']
errno: -2,
code: 'ENOENT',
syscall: 'open',
path:
'/Users/i012344/projects/rs/deploy/index.js/.env.json' }
I dont understand why it's happen as it's just like to a program which needs to read package.json as the package.json is in some generated project.
I doesnt works also for non-hidden file, not sure what Im missing here..., it should be rather simple, just read file from where your application is running
isn't it possible?
I can't understand why I'm getting this "Error: ENOENT" error. Here is my Meteor server method:
createImage: function(coords) {
console.log('createImage')
console.log(coords.area)
console.log(coords.x)
console.log(coords.y)
console.log(coords.x2)
console.log(coords.y2)
console.log(coords.w)
console.log(coords.h)
var gd = Meteor.npmRequire('node-gd');
var path = Meteor.npmRequire('path');
var fs = Meteor.npmRequire('fs');
var source = 'forrest.png';
var target = 'compimages';
if (path.exists(target)) fs.unlink(target);
gd.openPng(source, function(png, path) {
if(png) {
console.log(png)
console.log(path)
}
}
);
}
Here is the output I get from it on the terminal:
=> Meteor server restarted
I20140827-15:30:18.451(-7)? createImage
I20140827-15:30:18.455(-7)? 27888
I20140827-15:30:18.456(-7)? 242
I20140827-15:30:18.459(-7)? 164
I20140827-15:30:18.459(-7)? 410
I20140827-15:30:18.459(-7)? 330
I20140827-15:30:18.459(-7)? 168
I20140827-15:30:18.460(-7)? 166
W20140827-15:30:18.527(-7)? (STDERR) path.exists is now called `fs.exists`.
I20140827-15:30:18.547(-7)? { [Error: ENOENT, open 'forrest.png'] errno: 34, code: 'ENOENT', path: 'forrest.png' }
I20140827-15:30:18.548(-7)? undefined
These are the directories within ~/myapp/server/
me#ubuntu:~/myapp/server$ ls
compimages forrest.png privateimages server.js user-setup.js
I want to access forrest.png and use node-gd to cut a section of it out based on the coords passed in.
As far as I understand it this error means that there is a directory missing. The png file I'm trying to access is in the same directory as the .js file calling it (they are both in ~/myapp/server/ so to me it doesn't look like that's the problem. The only thing I can see is that the path is undefined. I've got that installed though:
me#ubuntu:~/myapp/packages/npm/npm/node_modules$ ls
node-gd path
Can anyone see what's going on with this? I'm using Meteor 0.9.0
If you console.log(process.cwd()) in your server code you will notice that the current working directory of your Meteor app is project/.meteor/local/build/programs/server however your code assumes that the CWD is project/server.
What you can do is prefixing your paths with the project root server folder which is obtained by going 5 level ups in the filesystem hierarchy.
var projectRootServer="../../../../../server";
var source=projectRootServer+"forrest.png";
This is not very elegant but it works.
Unrelated but it seems that path.exists has been deprecated in favor of fs.exists, you should fix this too.