I am trying to create a react component that reads from a .txt file with in my project and displays the text. Not sure where to start. I know how to call the component but not code for the component.
You must use a Node.js default module called fs
https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback
const fs = require("fs");
fs.readFile('myfile.txt', (err, data) => {
if (err) throw err;
// Do your stuff here
console.log(data);
});
If you are just trying to get values to pass into your React component then you can try turning it into a JSON file
and then
import data from '<path_to_json_file>';
Related
I'm trying to dynamically import from my dependencies using a for loop like so
const packageNames = [
'#packageA/address',
'#packageB/app',
'#packageC/auth',
]
for await (const packageName of packageNames) {
try {
const importedPackage = await import(`${packageName}/custom-components`);
console.log('importedPackage :', importedPackage);
// Do something with the imported package
} catch (error) {
console.error(`Error importing ${packageName}: ${error}`);
}
}
I want to import custom-components from those packageNames and if it fails just to catch the error and log it.
But instead, it breaks the app if the custom-components file doesn't exist in the package I'm trying to import from.
One solution I was thinking of would be to use the fs package to check if custom-components file exists in the package but that's not possible to do in a React app.
Is there any other way to get around this, to just catch the error instead of breaking the app with an error like Can't resolve '#packageA/address/custom-components'
I'm having a little problem, I have Web Push settings in one file called WebPush.ts and I want to import it to another file. but I'm getting an error.
WebPush.ts
import webpush from 'web-push'
export const WebPush = webpush.setVapidDetails(
`mailto:${process.env.ADMIN_EMAIL}`,
process.env.PUBLIC_VAPID_KEY!,
process.env.PRIVATE_VAPID_KEY!
)
and in another file I am importing it.
import { WebPush } from '../../Services/WebPush'
async somefunction(){
await WebPush.sendNotification(pushSubscripton, payload)
}
I'm getting this error:
Property 'sendNotification' does not exist on type 'void'.ts(2339)
But when I do settings in this file where I want to import this I Don't get error. How can I fix this?
I am trying to integrate the convertapi in my Angular 11 application using the following documentation
https://www.npmjs.com/package/convertapi
I need to convert the pdf's into images,
When I try to upload a file, I get
_path2.default.basename is not a function
Here is how I have implemented this in my component
Import
import ConvertAPI from 'convertapi';
Initiate
const convertapi = new ConvertAPI('my actual api-secret ');
And convert
convertapi.convert('jpg', { File: file }) //'file' is actual file object, also tried pdf url
.then(function(result: any) {
console.log(result)
})
.catch(function(e: any) {
console.log(e.toString()); // this prints out the error message
});
Is there anything I am missing?
This library is a non module, please refer to this question on how to use it with Angular:
Angular 2+ Import a Non Module into TS
This is the documentation: https://github.com/ConvertAPI/convertapi-js
I'm trying to write a basic local api for myself using Next.js, it is a timeline generator, and I am stuck at actually reading the file from the api folder.
What do I want in my local aplication:
1.A simple page where I can input an event, with a date and description
2.Open a list.json file somewhere and push that new event to that json file, writing on it.
What I am currently doing and where I am stuck:
I am aware we cant write on files on the client side, so I started looking at the api routes in next js to access the JSON file, but I cannot even manage to read it!
I have an api folder inside pages folder, and in this api folder I have two files: one is the list.json file, where I previously manually write some events with respective dates; and the other is getlist.js, with this code:
var fs = require('fs');
export default function getList(req, res) {
const rawList = fs.readFile('list.json');
var list = JSON.parse(rawList);
res.json(list);
}
Now on the pages folder I have a index.js file where I try to access this getlist.js api using getStaticProps(), like this:
import getlist from './api/getlist'
export async function getStaticProps(){
var list = getlist();
return {
props: {
list
}
}
}
I have tried using other stuff, like the fecth function, to get to getlist.js, but nothing I do seems to work.
Can anyone help me?
And since I'm already in here, how would I manage to get the input from the form I already have in my client side page and write it to that list.json file in my api folder?
There are two ways how you can read json in next.js:
Import inside getStaticProps [https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation]
export async function getStaticProps(context){
const example = await import('./api/example.json');
return {props: {example: example.default}}
}
Import or read in handler function inside api folder [https://nextjs.org/docs/api-routes/introduction]:
const fs = require('fs');
export default async function handler (req, res) {
const example = await fs.readFile('./example.json');
return res.status(200).json({example});
}
In order to write *.json file you need to send request with value to the server api (handler from api folder that was mentioned before).
That's how the part to write json will look like:
const fs = require('fs');
export default async function handler(req, res) {
//...
if (req.method === 'POST'){
fs.writeFileSync('./example.json', JSON.stringify(req.body))
return res.status(200).json({});
}
//...
}
I have this function to write a unit test, I have a .json file on the same folder to be passed as a parameter but how can I pass it as a parameter?
export const getColumnsFromJsonFile = async (file) => {
if (file?.type === 'application/json') {
const result = await new window.Response(file).json()
return Object.keys(result)
}
}
./test.json is just text, what I have to do to transform in a readable file by Response?
expect(await getColumnsFromJsonFile('./test.json')).toEqual([...])
Mock import of JSON file, You can either use moduleNameMapper in your jest settings to point the import to an mocked json file.
{ "moduleNameMapper": { "setting.json": Add jest-json to your Jest config: { " setupTestFrameworkScriptFile " : " jest-json " } Or if you're already using another test framework, create a setup file and require each of them:
How to import JSON file on Jest tests?, { something } from "../my-json.json"; How can I import the JSON file on Jest Note that myJSON is already an object, no need to use JSON.parse. Answer. Example 2: Python read JSON file. You can use json.load() method to read a file containing JSON object.. Suppose, you have a file named person.json which contains a JSON object.