This question already has an answer here:
Next.js: How to get static assets from within getStaticProps
(1 answer)
Closed 1 year ago.
I'm trying to pass a json file path to an ebay auth function to gain a token.
This works locally by stating the file name alone. However, as I have my next js app deployed as Node in Vercel, I need to call readFileSync to ensure the json file is included in the build.
To do that i've implemented: -
const { readFileSync } = require("fs");
var path = require("path");
const file = readFileSync(
path.join(__dirname, "config/eBayJson.json"),
"utf8"
);
in my getServerSideProps.
However, although my file is clearly at the right path, and I'm calling __dirname to ensure I have the right path. I'm still getting errors, now locally and in the vercel deployment that the file or directory does not exist: -
Error: ENOENT: no such file or directory, open '\config\eBayJson.json'
at Object.openSync (node:fs:490:3)
at readFileSync (node:fs:391:35)
at getServerSideProps (D:\Web\StoreApp\nextjs-store\.next\server\pages\inventory.js:3846:16)
at renderToHTML (D:\Web\StoreApp\nextjs-store\node_modules\next\dist\next-server\server\render.js:40:221)
at async D:\Web\StoreApp\nextjs-store\node_modules\next\dist\next-server\server\next-server.js:112:97
at async D:\Web\StoreApp\nextjs-store\node_modules\next\dist\next-server\server\next-server.js:105:142
at async DevServer.renderToHTMLWithComponents (D:\Web\StoreApp\nextjs-store\node_modules\next\dist\next-server\server\next-server.js:137:387)
at async DevServer.renderToHTML (D:\Web\StoreApp\nextjs-store\node_modules\next\dist\next-server\server\next-server.js:138:522)
at async DevServer.renderToHTML (D:\Web\StoreApp\nextjs-store\node_modules\next\dist\server\next-dev-server.js:35:578)
at async DevServer.render (D:\Web\StoreApp\nextjs-store\node_modules\next\dist\next-server\server\next-server.js:75:236)
at async Object.fn (D:\Web\StoreApp\nextjs-store\node_modules\next\dist\next-server\server\next-server.js:59:580) at async Router.execute (D:\Web\StoreApp\nextjs-store\node_modules\next\dist\next-server\server\router.js:25:67)
at async DevServer.run (D:\Web\StoreApp\nextjs-store\node_modules\next\dist\next-server\server\next-server.js:69:1042)
at async DevServer.handleRequest (D:\Web\StoreApp\nextjs-store\node_modules\next\dist\next-server\server\next-server.js:34:504) {
errno: -4058,
syscall: 'open',
path: '\\config\\eBayJson.json'
}
I'm at a loss for what I'm doing wrong. Most of the stack overflow answers I could find were about the lack of __dirname which I've already included.
Any help much appreciated!
SOLVED
Thanks to the help from #juliomalves and this thread: - https://stackoverflow.com/a/65861629/1870780, solved my problem with the updated code:
export async function getServerSideProps(req, res) {
const { readFileSync } = require("fs");
var path = require("path");
const configDirectory = path.resolve(process.cwd(), "config");
const file = readFileSync(
path.join(configDirectory, "eBayJson.json"),
"utf8"
);
const EbayAuthToken = require("ebay-oauth-nodejs-client");
const ebayAuthToken = new EbayAuthToken({
filePath: path.join(configDirectory, "eBayJson.json"),
// input file path.
});
Related
I am using this code and it works fine in simulator as I am getting a location and can get pdf file from there
async createPDF() {
let options = {
html: '<h1>PDF TEST</h1>',
fileName: 'test',
directory: 'Documents',
};
let file = await RNHTMLtoPDF.convert(options)
// console.log(file.filePath);
alert(file.filePath);
}
But the above code problem in the real iOS mobile as it is saving the pdf file somewhere. I don’t know where but I am not able to see that file in my mobile. So can anyone tell me how can I save my file in the downloads or documents in the iOS . So that I can see the downloaded file.
Found the answer to convert file in base64 string
You can solve this issue by using base64 as the following:
let options = {
html:
`
<h2 style="text-align: center">${'Some text and dynamic value'}</h2>
`,
fileName: 'TestingPDF',
directory: 'Documents',
base64: true
};
let file = await RNHTMLtoPDF.convert(options);
You shoud use 'react-native-file-access' to copy the file and move it to Downloads directory, so let's install it by: npm i react-native-file-access --save
Lets copy the file to the Downloads directory by the following:
const fileName = 'PMA_CurrentBalanceFile.pdf'; //whatever you want to call your file
const filePath = `${Dirs.DocumentDir}/${fileName}`;
const base64Data = file.base64; //our base64 encode file which done by RNHTMLtoPDF;
Then write the following code to do your job:
if (Platform.OS === 'android') {
const permissionGranted = await permissionWriteExternalStorage();
if (permissionGranted) {
await FileSystem.writeFile(filePath, base64Data, 'base64');
if (!FileSystem.exists(filePath)) return;// check to see if our filePath was created
await FileSystem.cpExternal(filePath, fileName,'downloads');// copies our file to the downloads folder/directory
// file should now be visible in the downloads folder
ToastAndroid.show("", "One File Downloaded", ToastAndroid.SHORT);
}
return;
}
if (Platform.OS === 'ios') {
// IOS version
await FileSystem.writeFile(filePath, base64Data, 'base64');
Alert.alert('', 'One File Downloaded');
}
I have a simple Electron app that should live in the tray. But on running it, I get the following warning:
(electron:5080): libappindicator-WARNING **: 23:21:11.078: Using '/tmp' paths in SNAP environment will lead to unreadable resources
This warning is probably due to the use or configuration of the iconPath the way I have. What does this warning ^ mean and what needs to be done to remove it?
This is my app's source:
const { app, Tray, Notification, Menu, nativeImage } = require('electron');
const path = require('path');
const iconPath = path.join(__dirname, 'assets/icons/iconTemplate.png');
let tray = null;
app.whenReady().then(() => {
try {
console.log(iconPath);
tray = new Tray(nativeImage.createFromPath(iconPath));
tray.setToolTip('Electron app');
} catch (e) {
console.log(e);
}
})
these day I'm new to node.js and leanrning them from Youtube vid
I had a plan to express image file to webbrowser
here is something wrong (I've already add image file in my folder)
and then I was trying to resolve this problem by searching google
but I hadn't found out.
It's first time to make a new account
it's the code
var http=require('http');
var fs = require('fs');
var server = http.createServer();
var host = '192.168.0.42';
var port = 3000;
server.listen(port,host,50000,function(){
console.log('웹서버 실행됨');
});
server.on('connection',function(socket){
var addr = socket.address();
console.log('클라이언트가 접속했습니다. : %s, %d', addr.address,addr.port);
});
server.on('request',function(req,res){
console.log('클라이언트 요청이 들어왔습니다.');
var filename = "coronavirus.png";
fs.readFile(filename, function(err,data){
res.writeHead(200, {"Content-Type":"image/png"});
res.write(data);
res.end();
});
});
your readFile needs to include an absolute or relative path.
try with a forward "/" as in /your_file_path or resolve with a cross-platform solution using __dirname + your file_path.
From the docs
fs.readFile('/etc/passwd', (err, data) => {
if (err) throw err;
console.log(data);
});
My main goal is to download a file from a link and then save it to the phone's internal storage so that it'll be accessible through the phone's file manager. I'm currently trying out Dio package by running the example code given in the package's repo. Upon running the program, I ran into a path problem. When I used ./example/flutter.png as the download path, I/flutter (10109): FileSystemException: Cannot open file, path = './example/flutter.png' (OS Error: No such file or directory, errno = 2) shows up. And when I used (await getApplicationDocumentsDirectory()).path which produces a String with the value of: /data/user/0/com.example.downloadexample/app_flutter as the path, no error showed up, but the file wasn't there. I tried different variation of the latter path, but with no success. Can someone help me with this problem?
Many thanks in advance.
I use http package, not the Dio, the code:
Future<String> fetchNetFileToDoc(String url, String filename) async {
final path = await getApplicationDocumentsDirectory();
File docFile = File('$path/$filename');
if(await docFile.exists()){
print( '${docFile.path} exits');
return docFile.path;
}
http.Response response = await http.get(url);
// todo - check status
await docFile.writeAsBytes(response.bodyBytes, flush: true);
return docFile.path;
}
if I invoke this method, like: fetchNetFileToDoc('http://a.com/a.mp3', 'a.mp3')
it shows the same error:
FileSystemException: Cannot open file, path= 'Direcotry: '/data/user/0/com.example.master_lu/app_flutter'/a.mp3' (OS Error: No such file or directory, errno = 2)
But if I use getTemporaryDirectory(), change code to this:
Future<String> fetchNetFileToTemp(String url, String filename) async {
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;
File tempFile = File('$tempPath/$filename');
if(await tempFile.exists()){
print( '${tempFile.path} exits');
return tempFile.path;
}
http.Response response = await http.get(url);
// todo - check status
await tempFile.writeAsBytes(response.bodyBytes, flush: true);
return tempFile.path;
}
That's ok, it works with the internal storage. Save the file into the data/user/0/com.example.master_lu/cache/a.mp3
The master_lu is the name of my project.
The latest=> I sovle my problem, await getApplicationDocumentsDirectory return Future<Directory>
so, here is the right code:
Future<String> fetchNetFileToDoc(String url, String filename) async {
final docDir = await getApplicationDocumentsDirectory();
String docPath = docDir.path;
File docFile = File('$docPath/$filename');
if(await docFile.exists()){
print( '${docFile.path} exits');
return docFile.path;
}
http.Response response = await http.get(url);
// todo - check status
await docFile.writeAsBytes(response.bodyBytes, flush: true);
return docFile.path;
}
The dart cookbook recipe 'Renaming a file, directory, or symlink' at https://www.dartlang.org/dart-vm/dart-by-example#renaming-a-file-directory-or-symlink doesn't seem to work as expected:
import 'dart:io';
main() async {
// Get the system temp directory.
var systemTempDir = Directory.systemTemp;
// Create a file.
var file = await new File('${systemTempDir.path}\\foo.txt').create();
// Prints path ending with `foo.txt`.
print('The path is ${file.path}');
// Rename the file.
await file.rename('${systemTempDir.path}\\bar.txt');
// Prints path ending with `bar.txt`.
print('The path is ${file.path}');
}
The output shows that the internal path field of the file object has not been changed (although the rename is successful):
[Running] dart "d:\src\dart\renameAsOnWeb.dart"
The path is C:\Users\guivh\AppData\Local\Temp\foo.txt
The path is C:\Users\guivh\AppData\Local\Temp\foo.txt
[Done] exited with code=0 in 0.327 seconds
I have extended / reworked the cookbook example to further investigate this:
import 'dart:io';
main() async {
var systemTempDir = Directory.systemTemp;
var file = await new File('${systemTempDir.path}\\foo.txt').create();
print('The file is located at ${file.path}');
File toDelete;
var newName = '${systemTempDir.path}\\fubar.toodeloo';
await file.rename(newName);
if (await new File(newName).exists() == false) {
print('The rename failed: there is no ${newName} file');
} else {
var newFile = new File(newName);
print('The rename was succesful');
var nameChangedInObject = file.path == newName;
if (nameChangedInObject) {
print('The path of the file object has changed correctly');
toDelete = newFile;
} else {
print(
'The path in the file object still is: ${file.path}');
toDelete = newFile;
}
await toDelete.delete();
print(
'And now, ${toDelete.path} is gone: ${await toDelete.exists() == false}');
}
}
And this output confirms the fact that the internal path field is not updated with the new name:
[Running] dart "d:\src\dart\renamingExample.dart"
The file is located at C:\Users\guivh\AppData\Local\Temp\foo.txt
The rename was succesful
The path in the file object still is: C:\Users\guivh\AppData\Local\Temp\foo.txt
And now, C:\Users\guivh\AppData\Local\Temp\fubar.toodeloo is gone: true
[Done] exited with code=0 in 0.369 seconds
I am runing the dev version on a windows box:
PS D:\src\dart> dart --version
Dart VM version: 2.0.0-dev.39.0 (Fri Mar 16 00:17:07 2018 +0100) on "windows_x64"
PS D:\src\dart>
Can somebody please explain what is going on here?
The example is wrong. The File object is immutable, so it definitely won't be changed by the rename operation. The example is wrong in expecting so.