Blogs
Explore our diverse collection of insightful blogs, covering topics ranging from technology trends and industry insights to practical tips.
- Home
- Blogs
How to import json file in Angular
Hello Everyone!!! In this post, we will learn how to read json file in angular. We will cover 3 different ways to import and read local json file. We will get below output at the end of every method of reading json file. output of the story First Way Angular 6.1+ supports TypeScript 2.9+ which allows you to use the import statement to import local JSON files just like any TypeScript module. So we can use this below feature in any Angular application which has used TypeScript 2.9+. To enable this feature, follow the below steps. Step 1 : Create your JSON file in your project wherever you want. We will create a new folder called json and under that folder, create a new file called data.json. So it’s path looks like src/assets/json/data.json. Step 2 : Set the resolveJsonModule: true & esModuleInterop: true in the tsconfig.json file under the compilerOptions key. So tsconfig.json will look like { ..., "compilerOptions": { ..., "resolveJsonModule": true, "esModuleInterop": true } } Where --resolveJsonModule allows for importing, extracting types from .json files. --esModuleInterop allows default imports from modules with no default export. This is required since a .json file has no default output. Step 3 : Now you can import JSON file in your components/directives/services wherever you want with // PATH TO YOUR JSON FILE import data from '../../assets/json/data.json'; Second Way The second way that you can use to import JSON files in your Angular application is Angular HttpClient. Step 1 : Create your JSON file in your project wherever you want. We will create a new folder called json and under that folder, create a new file called data.json. So it’s path looks like src/assets/json/data.json. Step 2 : Import HttpClientModule in app.module.ts file. So it’s code looks like import { HttpClientModule } from '@angular/common/http';@NgModule({ imports: [..., HttpClientModule] }) export class AppModule {} Step 3 : Now you can import JSON file in your components/directives/services with making Http call like import { Component } from '@angular/core'; import { HttpClient } from '@angular/common/http';@Component({ selector: 'app-second-way', template: `<div>{{jsonDataResult | json}}` }) export class SecondWayComponent { jsonDataResult: any; constructor(private http: HttpClient) { this.http.get('assets/json/data.json').subscribe((res) => { this.jsonDataResult = res; console.log('--- result :: ', this.jsonDataResult); }); } } Third Way We have one more way to import local JSON files using the ES6+ import statement which supports importing JSON files. Step 1 : Create your JSON file in your project wherever you want. We will create a new folder called json and under that folder, create a new file called data.json. So it’s path looks like src/assets/json/data.json. Step 2 : Create a typing file *.d.ts where your JSON file created. In our case, we will create data-typings.d.ts under src/assets/json folder. So it’s path looks like src/assets/json/data-typings.d.ts. It’s code looks like declare module '*.json' { const value: any; export default value; } Step 3 : Now you can import JSON file in your components/directives/services wherever you want with // PATH TO YOUR JSON FILE import * as data from '../../assets/json/data.json'; // OR Import it like // import data from '../../assets/json/data.json'; GitHub Repository Below is our GitHub repository link where you can download this working example. codeptivesolutions/import-read-json-files Thanks!!! Did you find your solution or learn something new? If so please: clap 👏 button below️ as many times as you can and share this post with others. Follow us on Medium to read more articles about Python, Angular, React, Vue, Node JS. You can leave your feedback/suggestions in the comments 💬 below. Would you like to check out our other articles? What is Progressive Web App(PWA)? Understand PWA concept in few minutes!!! Want to check Node version before project get executed using script!!! How to import json file in Angular was originally published in CodeptiveSolutions on Medium, where people are continuing the conversation by highlighting and responding to this story.
By Codeptive Solutions
Auto Code Formatting with prettier and jsbeautify on git pre commit hook
Hello Everyone!!! In this story, We will learn how to perform automatic code formatting for HTML, CSS, Sass, Scss, JavaScript, TypeScript, JSON, etc files with prettier and js-beautify on git pre-commit hook using husky and lint-staged. We can do this auto code formatting on any projects/applications which based on NPM(Node package manager). Simply it means we can integrate this on any project which contains a package.json file 😃!!! No matter whether the project is based on Angular, VueJs, ReactJs, or any other frameworks. We will get this output at the end of this story. Output of the Story We will use prettier to do code formatting for file types like TypeScript(ts), JavaScript(js), CSS, Sass(Scss), Less, JSON, JSX, GraphQL, YAML, etc except HTML file because it is in the trial phase at the time of this article creation. js-beautify to do code formatting for HTML file types. lint-staged to do code formatting only against staged git files and don’t let slip into your entire code base! husky to run our auto code formatting things on git pre-commit hook so that on each commit we make sure all committed code will be formatted with our defined custom formatting rules no matter developers installed these formatting plugins(prettier, js-beautify) on their machine or not! Why we need this? For large projects with multiple developers, different developers prefer a different code format or they have their own code formatting settings in their IDE or CLI tools (remember, tabs vs space). So we are often facing problems like While committing code, our IDE shows us lots of unnecessary git diff of white spaces even if we changed only one line. Sometimes it becomes a pain for us to derive what actually changed in code. PR reviewers also facing problems while reviewing PR. He/She could not do focus on actual code changed logic. So contributors often do the first iteration of PR goes in fixing the styling related problems. One global common central code formatting rules are not maintaining. We are not investing our time where we need to because of some styling related problems and this makes our speed slower. Benefits Your codebase is written in one consistent style, no matter how many developers collaborate on it and they installed formatting plugins(prettier, js-beautify) on their machine or not! Half of your code style guide isn’t needed anymore. Why teach yourselves about tabs or spaces, when it will be reformatted automatically anyways? Leave the code style to robots. Focus on the code instead. You will write your code faster. Remember those times when you had to ENTER a new line every time you wanted to call another method? Or you had to wonder for 10 seconds about whether to keep your array in one line or multi-lines? Forget about it now. The IDE will do it for you. You can focus on the code, not the style, in your code reviews. Skip having rarely effective and totally-not-fun discussions like “I think we ought to use additional parentheses here. This is a bit too unreadable now.”. Enjoy having more time and energy, and when reviewing PRs, focus on what is most essential in them: their introduced code and its’ logic. All in all, it will improve your codebase and help you avoid bugs. Because even if it just means tidying up your spaces, it also means this: your code will be much clearer, and you’ll have more time to focus on your code, not anything else. Can’t wait to do this… Let’s start Install prettier, js-beautify, lint-staged & husky as devDependencies by running command npm i prettier js-beautify lint-staged husky --save-dev Create .prettierrc file in root of your project. Define your own code formatting custom configurations in that file like { "printWidth": 80, "tabWidth": 2, "useTabs": false, "singleQuote": true, "trailingComma": "all", "bracketSpacing": true, "arrowParens": "always", "jsxBracketSameLine": false, "semi": true } You can find more available configuration options on https://prettier.io/docs/en/options.html Create .prettierignore file in root of your project. Define files, folders which you don’t wanna formats like node_modules/* e2e/* dist/* src/assets/scss/bootstrap/* Create .jsbeautifyrc file in root of your project. Define your own HTML code formatting custom configurations in that file like { "editorconfig": false, "indent_size": 2, "end_with_newline": true, "html": { "brace_style": "collapse", "indent_char": " ", "indent_scripts": "normal", "indent_inner_html": true, "indent_empty_lines": false, "wrap_line_length": 120, "wrap_attributes": "force-expand-multiline", "unformatted": [ "sub", "sup", "b", "i", "u", "em", "strong" ], "preserve_newlines": true, "max_preserve_newlines": 2 } } You can find more available configuration options on https://github.com/HookyQR/VSCodeBeautify/blob/master/Settings.md Create npm scripts & setup husky, lint-staged in package.json like { ..., "scripts": { ..., "format": "npm run format:prettier && npm run format:html", "format:prettier": "prettier --config .prettierrc \"src/**/*.{ts,css,less,scss,js}\" --write", "format:html": "js-beautify --config .jsbeautifyrc --type 'html' --file 'src/**/*.html' --replace" }, "dependencies": { ... }, "devDependencies": { "husky": "^4.2.3", "js-beautify": "^1.10.3", "lint-staged": "^10.0.8", "prettier": "^1.19.1" }, "husky": { "hooks": { "pre-commit": "lint-staged" } }, "lint-staged": { "*.{ts,css,less,scss,js}": [ "prettier --config .prettierrc --write", "git add" ], "*.html": [ "js-beautify --config .jsbeautifyrc --type 'html' --replace", "git add" ] } } That’s it!!! Now code will be automatic formatted before each commit without worrying OR you can manually run “npm run format” in your terminal to do formatting for all file types. GitHub Repository Below is our GitHub repository link where you can download this working example. codeptivesolutions/auto-code-formatting Thanks!!! Did you find your solution or learn something new? If so please: clap 👏 button below️ as many times as you can and share this post with others. Follow us on Medium to read more articles about Python, Angular, React, Vue, Node JS. You can leave your feedback/suggestions in the comments 💬 below. Would you like to check out our other articles? What is Progressive Web App(PWA)? Understand PWA concept in few minutes!!! Want to check Node version before project get executed using script!!! CRUD operations with Google Drive in Python using google-api-python-client Auto Code Formatting with prettier and jsbeautify on git pre commit hook was originally published in CodeptiveSolutions on Medium, where people are continuing the conversation by highlighting and responding to this story.
By Codeptive Solutions
What is Progressive Web App(PWA)? Understand PWA concept in few minutes!!!
In this tutorial, we will see what is Progressive Web App(PWA), what are advantages of using PWA, why do we need PWA instead of Mobile Native Apps, should we use PWA for our Web App, can we convert our static(HTML/JavaScript) Web App or SPA Angular, React, Vue Web App or any other Web App into Progressive Web App? What is Progressive Web App(PWA)? You probably saw that PWA is an extremely super hot topic these days. Everyone talks about Progressive Web App. so what is PWA or Progressive Web App? Well PWA is nothing but Progressive Web App. It is a set of technologies or techniques that allows doing one special thing which is you can progressively enhance your Web App to look and feel like Mobile Native App while still saying a Web App. So In the end, PWA is just a term which refers to a couple of features that you can add to any web app, to any web page running on the browser to enhance it. PWA totally runs independently no matter your app is built in Single Page Application with Angular, React, Vue or Multi-Page Application with static HTML/JavaScript, Node, PHP, etc. so you can turn any Web App which runs on the Web Browser into PWA to progressively enhance it. Progressively enhance Web Apps mean it does not just look and feel like Native Apps(Not talking about responsive designs which we already learned a few years ago). we are talking about like App working even when you are Offline It having an Icon on the Home Screen Things like accessing Device Camera or Location Synchronizing Data in the Background These are all features that are hard to do in Web Applications in the past but now a day we get all most of browsers to support therefore we can use the PWA in our Web App easily. It still works on older browsers too but if you have a modern browser then you will get an awesome experience. What are the advantages of PWA? What the PWA offers? It has some advantages to use PWA in your Web App like Be reliable: Load fast and provide offline functionality(At least part of the application should work if you are offline). Fast: Respond quickly to user actions. Engaging: Feel like a Native App on Mobile Devices. We can bring our users back on our app with Push Notifications even our app is closed. We can access a Device Camera, Location via PWA. so It’s like you can do things which you do in Native Apps. PWA offers you that you can add it in your existing Web Application to turned them into Native Mobile App like experiences via using Install on Home Screen Service Worker Caching, Caching Dynamic API Data (Offline Access) Offline Accessibility Background Syncing Background Syncing Web Push Notifications Media API (Camera & Geo location) Mobile Web Browser Apps VS Mobile Native Apps As per the survey, Users spent most of their time in Mobile Native Apps instead of Mobile Web Browser. Users spent their 87% time in Mobile Native Apps & 13% time in Mobile Web Apps. These counting show us a large difference. Why users spent most of their time in Mobile Native Apps instead of Mobile Web Apps because Mobile Native Apps are able to provide Push Notifications bring users back to the Native App Home Screen Icons make access to easy for users Access Native Device features like Camera, Geo location, etc Possibly work Offline(At least some part of application work offline) We can do all these things in our Web Apps also with PWA. Why we should choose PWAs over Mobile Native Apps? As you saw, Users spent their 87% time in Mobile Native Apps. Ya, that’s right but users spent their huge time in top 3 Apps on mobile devices probably Google, Facebook, Whats App, Instagram whatever user’s favourite, probably it won’t include your app in top 3 Apps. so when the users get time to look at our App? Users reach to Web Pages much more compared to Native Apps. so in the Web, we have a broader audience and visitors and because of the users spent 87% time on top 3 Native Apps, the same Apps, The New App doesn’t get new visitors in Native Apps. so this is one of the reasons that we should think about PWAs and use it. What you think about how much the average time users spent on the Play Store OR App Store to install our new App rather than use popular and favourite App? It’s probably less than 10%. If you build a Mobile Native App, then you must learn different languages like Java, Objective-C, Ionic, React Native, Flutter, etc if you want to support both Android & IOS. so why you don’t build your App in that which you already know like HTML, CSS, JavaScript, etc. Because of these reasons, PWA is a better option compared to Mobile Native Apps. PWAs VS Native Apps VS “Traditional” Web Apps PWAs VS Native Apps VS “Traditional” Web Apps PWA Core Building Blocks Now let’s talk about core building blocks, technologies, techniques which are used while building PWAs. Service Workers Application Manifest Responsive Design Media API (Camera & Geo location) Service Workers(SW): This is a core feature. Service Workers are supported in modern browsers like Chrome, Firefox, Opera, etc and service workers are basically JavaScript running in the background process even if your application is closed. SW is core building blocks because it allows us to get offline access to cache some files and serve them if we don’t have an internet connection and they give us access to other PWAs related features e.g. Caching/Offline Support(First browser would check on cache If it is not found then and then it will go for check in the Network) Background Sync(Sync user data in the background and store it in a way that even if your app close still it can send data to server when re-establish internet connection) Web Push(It’s a Mobile Push Notifications. We can get Push Notifications in a way that even if our app is closed) Enable other PWA features Service Workers Application Manifest: This technique allows users for addition to the Home Screen. The Application Manifest makes your app installable on the Home Screen, Not installed through App Store still you will see it like normal Native App. App Manifest file is a kind of document which tells the browser about our App. Responsive Design: App/Layout should work and look good across Devices. Media API (Camera & Geo location): Access Device Camera, Microphone, User location, etc. These features which make PWAs are well supported already. You can reach a huge audience with all these features and the cool thing is you can make PWAs in way that your Web App would still work in older browsers also. Now it’s time to be prepared for a future where probably every Web App will be a PWA since it offers significant advantages and make your application much more enjoyable to your users. Progressive Enhancement What if we want to add PWA features in our older project. We can’t and don’t write our app from scratch right? Well, you can add some PWA features in your app for making your app as PWA. It isn’t necessary to add a 100% or 0% PWA features. You can add absolutely 40% or 60% features means you can add features whichever you want of PWA in your app. We can add PWA features step by step and you can stop it at any given point. You can stop after adding just Application Manifest and Basic Service Workers files, you can stop after adding Install on Home Screen, Basic Caching, Advanced Caching, Push Notifications, Geo location API, Media API, etc. Some people are looking out this technology and saying that I don’t have the resources or time to rebuild my app and they need to support their app in older browsers anyway. I want to answer you that that’s not a problem. You can add whatever you want to add features that enhance your app. Summary so we learned that PWA is just a set of technologies or techniques. It is a platform independent therefor you can turn any Web App which runs on the Web Browser into PWA to progressively enhance it no matter it is built on Angular, React, Vue, Node, PHP, HTML/JavaScript, etc. With one language or framework, we can make our App as Web App + almost Mobile Native App with the use of PWA. With PWA, we can get awesome features like Offline Access, Basic Caching, Advanced Caching, Install on Home Screen(Like Mobile Native App Icon on Home Screen), Background Synchronization, Access Device Camera, Geo location, etc. We can add PWA in our existing projects as well as new projects. It is not necessary to add 100% features of PWA, We can stop after adding 20% or 40% features. We can stop after just Install on Home Screen or Basic Caching or Advanced Caching or Push Notifications or Geo location API, Media API, etc. Now it’s time to be prepared for a future where probably every Web App will be a PWA since it offers significant advantages and make your application much more enjoyable to your users. Thanks!!! Did you find your solution or learn something new? If so please: clap 👏 button below️ as many times as you can and share this post with others. Follow us on Medium to read more articles about Python, Angular, React, Vue, Node JS. You can leave your feedback/suggestions in the comments 💬 below. Would you like to check out our other articles? How to import json file in Angular Want to check Node version before project get executed using script!!! What is Progressive Web App(PWA)? Understand PWA concept in few minutes!!! was originally published in CodeptiveSolutions on Medium, where people are continuing the conversation by highlighting and responding to this story.
By Codeptive Solutions
CRUD operations with Google Drive in Python using google-api-python-client
Hey Everyone! In this story, we will learn to integrate the google-api-python-client library in python for file operation with google drive like upload file, download file, get file details and delete the file. 🔧 Setup google-api-python-client library We need to install the google-api-python-client library of the python for these CRUD operations. pip install google-api-python-client 2. Google Service Account We need a google service account for this and this is a reference to create a service account in the google developer console. After creating a service account we will get a JSON file like below and we will use this JSON file for the operations with google drive. Sample JSON file of the google service account. https://medium.com/media/83c2d1b9b78e6aa0210b4efc6a1d63f4/href For accessing any folder using this service account, we need to grant write access to service account email test-456@vernal-isotope-253109.iam.gserviceaccount.com from the service-account.json file. So, I created a demo folder called “Google Drive Demo” and grant write access to it. Also for any operations, we need a google folder id of Google Drive Demo folder and that I copied from URL as highlighted in the below screenshot. 3. Enable Google Drive API We need to enable drive API for a project of this service account. This is a reference link to enable google drive API. So, Let’s start with an upload file operation. 🔼 UPLOAD FILE In this section, we will create a function that will upload any files from local machine to Google Drive Demo folder of the drive. https://medium.com/media/337088c960c21cb0716b478e6ec54d92/href This code will upload 4 different files in the Google Drive Demo folder. Make sure you replaced parent_folder_id with your Google Drive Folder Id. Below is the output of the above code. Console output: {'kind': 'drive#file', 'id': '1CLrXti7-sFYQ7jeAkbJIiFwi3RmLNRXH', 'name': 'google-logo.jpg', 'mimeType': 'image/jpeg'} {'kind': 'drive#file', 'id': '1HVom1UX6RZU0wqZM-pYfDshvhEWz2Ifm', 'name': 'download.png', 'mimeType': 'image/png'} {'kind': 'drive#file', 'id': '1ePZiPxNN0z3qNOXPFT4GHDW-4CPQEEa2', 'name': 'sample.pdf', 'mimeType': 'application/pdf'} {'kind': 'drive#file', 'id': '18TU2hENa4bKi3HSXUllcSca3swC3OXMw', 'name': 'file-sample_100kB.doc', 'mimeType': 'application/msword'} Uploaded files to Google Drive Demo folder ⬇️ DOWNLOAD FILE In this section, We will download files that were uploaded from the above code. We need google file id to download the file and we can get it from a shareable link of google document. Get shareable link The link will look like this https://drive.google.com/open?id=1HVom1UX6RZU0wqZM-pYfDshvhEWz2Ifm. The download_file() of the code will take the below parameters. Id of the google file and we can get that from the above shareable link. Local folder path to save the downloaded files. https://medium.com/media/852c7b4406f4937a832e717a0f9b75fe/href The above code will download all uploaded files. Make sure you replaced parent_folder_id with your Google Drive Folder Id. Console output: Download 100%. Download 100%. Download 100%. Download 100%. Downloaded files 📔 GET FILE DETAILS In this section, we will fetch details of the uploaded files. https://medium.com/media/001e983dc934589028c4daa32c823895/href This code will print details of the file. The fields parameter is passed to get specific fields in the response. Make sure you replaced parent_folder_id with your Google Drive Folder Id. Console output with different fields value: fields = None {'kind': 'drive#file', 'id': '1CLrXti7-sFYQ7jeAkbJIiFwi3RmLNRXH', 'name': 'google-logo.jpg', 'mimeType': 'image/jpeg'} fields = “id,name,mimeType,webViewLink,createdTime,modifiedTime, size” {'id': '1CLrXti7-sFYQ7jeAkbJIiFwi3RmLNRXH', 'name': 'google-logo.jpg', 'mimeType': 'image/jpeg', 'webViewLink': 'https://drive.google.com/file/d/1CLrXti7-sFYQ7jeAkbJIiFwi3RmLNRXH/view?usp=drivesdk', 'createdTime': '2019-12-03T07:55:14.663Z', 'modifiedTime': '2019-12-03T08:25:22.628Z', 'size': '28031'} fields = “*” {'kind': 'drive#file', 'id': '', 'name': 'google-logo.jpg', 'mimeType': 'image/jpeg', 'starred': False, 'trashed': False, 'explicitlyTrashed': False, 'parents': [''], 'spaces': ['drive'], 'version': '3', 'webContentLink': '', 'webViewLink': '', 'iconLink': '', 'hasThumbnail': True, 'thumbnailLink': '', 'thumbnailVersion': '1', 'viewedByMe': False, 'createdTime': '2019-12-03T07:55:14.663Z', 'modifiedTime': '2019-12-03T08:25:22.628Z', 'modifiedByMeTime': '2019-12-03T07:55:14.663Z', 'modifiedByMe': True, 'owners': [{'kind': 'drive#user', 'displayName': 'test-456@vernal-isotope-253109.iam.gserviceaccount.com', 'me': True, 'permissionId': '', 'emailAddress': 'test-456@vernal-isotope-253109.iam.gserviceaccount.com'}], 'lastModifyingUser': {'kind': 'drive#user', 'displayName': '', 'photoLink': '', 'me': False, 'permissionId': '', 'emailAddress': '<email>'}, 'shared': True, 'ownedByMe': True, 'capabilities': {'canAddChildren': False, 'canChangeCopyRequiresWriterPermission': True, 'canChangeViewersCanCopyContent': True, 'canComment': True, 'canCopy': True, 'canDelete': True, 'canDownload': True, 'canEdit': True, 'canListChildren': False, 'canModifyContent': True, 'canMoveItemIntoTeamDrive': True, 'canMoveItemOutOfDrive': True, 'canReadRevisions': True, 'canRemoveChildren': False, 'canRename': True, 'canShare': True, 'canTrash': True, 'canUntrash': True}, 'viewersCanCopyContent': True, 'copyRequiresWriterPermission': False, 'writersCanShare': True, 'permissions': [{'kind': 'drive#permission', 'id': '', 'type': 'user', 'emailAddress': '<email>', 'role': 'writer', 'displayName': '', 'photoLink': '', 'deleted': False}, {'kind': 'drive#permission', 'id': 'anyoneWithLink', 'type': 'anyone', 'role': 'reader', 'allowFileDiscovery': False}, {'kind': 'drive#permission', 'id': '', 'type': 'user', 'emailAddress': 'test-456@vernal-isotope-253109.iam.gserviceaccount.com', 'role': 'owner', 'displayName': 'test-456@vernal-isotope-253109.iam.gserviceaccount.com', 'deleted': False}], 'permissionIds': ['', 'anyoneWithLink', ''], 'originalFilename': 'google-logo.jpg', 'fullFileExtension': 'jpg', 'fileExtension': 'jpg', 'md5Checksum': '664c8a61ad7d772f0a7198f9274f5cf9', 'size': '28031', 'quotaBytesUsed': '28031', 'headRevisionId': '', 'imageMediaMetadata': {'width': 820, 'height': 475, 'rotation': 0}, 'isAppAuthorized': True} ❎ DELETE FILE In this section, we will delete file from Google Drive Demo folder. https://medium.com/media/2fcf2110aeaafe71faa40227c88ee929/href This code will delete the download.png file. Make sure you replaced parent_folder_id with your Google Drive Folder Id. Console output: File deleted successfully. download.png deleted from the Google Drive Demo folder That’s it for this one. Thank you for reading this ❤️ If you find this post useful, press👏 button as many times as you can and share this post with others. You can leave your feedback/suggestions in the comments 💬 below. For future posts of this series, you can follow me on medium to receive post updates. 🔔 Would you like to check out other useful articles? What is Progressive Web App(PWA)? Understand PWA concept in few minutes!!! Prefetch Related and Select Related in Django Commonly used SQL queries using Django ORM CRUD operations with Google Drive in Python using google-api-python-client was originally published in CodeptiveSolutions on Medium, where people are continuing the conversation by highlighting and responding to this story.
By Codeptive Solutions
To know Coronavirus update, Coronavirus tips, Coronavirus prevention, WHO introduced WhatsApp…
To know Coronavirus update, Coronavirus tips, Coronavirus prevention, WHO introduced WhatsApp Helpline Chatbot https://medium.com/media/3870787fb043b86295734dd59ac859bb/href As we all know that today’s world is facing the most difficult situation of Coronavirus disease (COVID-19). Everyone wants to know about the updates of coronavirus, Symptoms of coronavirus, Latest situation dashboard of coronavirus, How we can protect ourselves, which things we should do, which things we should not do? But is there any source available to easily know? The answer is Yes. Coronavirus (COVID-19) There are thousands of sources available on the internet for these things but I believe most trustable information, updates are available on WHO(World Health Organization). Its official website is https://www.who.int/ How WHO can help us to know the answer to all our questions about Coronavirus disease? Well, we can know easily our answer without any hesitation by doing WhatsApp chatting with WHO. WHO introduced one WhatsApp Helpline number where we can chat with them. Well, it is one kind of chatBot, not a real human being. So it could not do chat as we human beings do but it is capable to give us the most common answer which frequently asked by people. It is one kind of automated system. Just say “hi” to “+41 22 501 76 15” WhatsApp Number Just save this “+41 22 501 76 15” contact number by giving some name in your mobile phone. Let’s save this number as WHO. Open your WhatsApp. Find that saved name For E.g. “WHO” and click on it to start the chat. Just type “hi” OR “Hi” OR “Hello”, It will give a response with an ordered list. Just type the index number OR emoji which you want to know about it. For e.g. type “2” OR “👍”. It will advise about “Protect yourself”. Just type “0” to go for Main Menu. This is available in many languages also. This can be found in its response. These things you could know in its response. So don’t worry about it. Just read it’s response carefully and type the according to number OR emoji to know about your question. You can see the video https://youtu.be/2ywBFiw9CcM to know more about how we can do this. I hope this will help every people in this world who doesn’t know about it yet. So please share this article OR video as much as you can, so we can help other people around the world from this Coronavirus disease (COVID-19). Thanks!!! To know Coronavirus update, Coronavirus tips, Coronavirus prevention, WHO introduced WhatsApp… was originally published in CodeptiveSolutions on Medium, where people are continuing the conversation by highlighting and responding to this story.
By Codeptive Solutions
Working with excel of json data in VueJs using xlsx and bootstrap-vue
In this story, I will demonstrate how to download an excel file of JSON data with Vue JS. We will use the bootstrap-vue and xlsx javascript library for this demo. We will get this output at the end of this story. The output of the story So, Let’s start with project creation. Project Setup Install vue-cli using npm command. npm install -g @vue/cli Create a project using the below command. vue create demo The above command generates a project in a directory/folder demo. You can learn more about this command from here. Project structure This project contains a default code for VueJs App. Here is an image that shows the file structure of the generated demo project. Delete HelloWorld.vue default generated component because we don’t need it. Now run below command npm run serve This command will run your project on localhost port 8080. Below is the output of the localhost:8080. localhost:8080 Create a component Create a file with the name ExcelDownloadDemo.vue inside the src/components folder. The component is ready to use. Now we will add code to the newly created component. We need to install a bootstrap-vue library to use a bootstrap table. This is optional. npm install bootstrap-vue --save Here is a base code for this demo. I have added a table with some static data and download button to download table data as excel xlsx. https://medium.com/media/9052a0e67235e2b9c76ffcb3accca9fe/href Also, I have updated the App.vue file to render ExcelDownloadDemo.vue as below. https://medium.com/media/02f4d5b57c940b58fecc58e62624c06c/href Run npm run serve and check the output. You will able to see as shown below on the localhost. Output without download functionality Now Let’s add download functionality to the Download button. For that, we need to install the xlsx library for this. You can download using the below command. npm install xlsx --save When a user clicks download we will execute a function to convert JSON to excel and download that excel after conversion. Below is the updated ExcelDownloadDemo.vue file. https://medium.com/media/1da8bc89db512d0d8c797b2f6006e8a0/href Here, I’ve added below things to existing ExcelDownloadDemo.vue. Add v-on: click to download button Import BTable and xlsx inside the <script> tag. Register BTable inside the components. Add download method inside the methods. Run npm run serve and check the output. You will able to download the xlsx file which contains a table data. Well, this is it! I hope you liked it. Thanks!!! Did you find your solution or learn something new? If so please: clap 👏 button below️ as many times as you can and share this post with others. Follow us on Medium to read more articles about Python, Angular, React, Vue, Node JS. You can leave your feedback/suggestions in the comments 💬 below. Would you like to check out our other articles? Want to check Node version before project get executed using script!!! What is Progressive Web App(PWA)? Understand PWA concept in few minutes!!! Working with excel of json data in VueJs using xlsx and bootstrap-vue was originally published in CodeptiveSolutions on Medium, where people are continuing the conversation by highlighting and responding to this story.
By Codeptive Solutions
Want to check Node version before project get executed using script!!!
Hello Everyone!!! In this post, we will learn how to check Node version of a system using a script and if the system’s Node version is not compatible with our project’s required Node version then forcefully stop npm package installation(npm install) as well as project startup command(npm start) and notify developers about this issue. We will get below output at the end of the story. output of the story Problem Sometimes our projects are depended on a specific Node version, If developers didn’t install that specific Node version then they might face some issues. E.g. Node Async/Await. If we used Async/Await in our projects then we need Node 8+ version otherwise it wouldn’t work as expected. So how our project team especially developers will know which Node version they should install and start the development? Let’s discuss its solution! Solution 1: Manual Solution but such a pain… We have to tell each and every team member that please use this Node version otherwise, it won’t work properly. So the problem is we need to tell everyone ourselves manually. Solution 2: Use common approach but not getting satisfaction… People generally use engines in package.json file to specify required Node Version. { "engines" : { "node" : ">=8.0.0 <11.0.0" } } People often use .nvmrc to specify Node version. People often describe which Node version required for the project in README.md file But the problem in the above approaches is if developers didn’t install project required Node version, still developers could be able to install project dependencies via “npm install” and could go further. It doesn’t check forcefully. So why we don’t make a script which solves our problem. That’s a cool idea, Isn’t it!! Jackpot Solution: Check with our own custom script So first of all, Let’s write a script for check Node Version of system. Step 1 : Create one JavaScript file in root directory like checkNodeVersion.js const result = process.versions; if (result && result.node) { if (parseInt(result.node) >= 8) { console.log("\x1b[47m\x1b[32m%s\x1b[0m", "-------******* Good to Go with your Node Version: " + result.node + " *******-------"); } else { console.log("\x1b[47m\x1b[31m%s\x1b[0m", "-------******* Package installation(npm install) or Project startup command(npm start) failed due to Node Version, Please install and use Node Version >=8 *******-------"); console.log("\x1b[47m\x1b[33m%s\x1b[0m", "-------******* Your current Node Version is: " + result.node + " *******-------"); process.exit(1); } } else { console.log("\x1b[47m\x1b[31m%s\x1b[0m", "-------******* Something went wrong while checking Node version *******-------"); process.exit(1); } NOTE: In console.log(), %s is wherein the string (the second argument) gets injected. \x1b[0m resets the terminal color so it doesn’t continue to be the chosen color anymore after this point. For More Colors Reference: // General settings: Reset = "\x1b[0m" Bright = "\x1b[1m" Dim = "\x1b[2m" Underscore = "\x1b[4m" Blink = "\x1b[5m" Reverse = "\x1b[7m" Hidden = "\x1b[8m" // Foreground colors: FgBlack = "\x1b[30m" FgRed = "\x1b[31m" FgGreen = "\x1b[32m" FgYellow = "\x1b[33m" FgBlue = "\x1b[34m" FgMagenta = "\x1b[35m" FgCyan = "\x1b[36m" FgWhite = "\x1b[37m" // Background colors: BgBlack = "\x1b[40m" BgRed = "\x1b[41m" BgGreen = "\x1b[42m" BgYellow = "\x1b[43m" BgBlue = "\x1b[44m" BgMagenta = "\x1b[45m" BgCyan = "\x1b[46m" BgWhite = "\x1b[47m" You can modify the logic of script based on your requirements. It’s totally up to you. Step 2 : Now our script is ready, we just need to find the place where we can inject. We will use the preinstall as well as prestart script of npm so that our custom “checkNodeVersion” script runs before execute npm install as well as npm start. You can find more places on https://docs.npmjs.com/misc/scripts. So update your package.json file like { "name": "...", "version": "...", "scripts": { "preinstall": "node checkNodeVersion", "prestart": "node checkNodeVersion", ... }, "dependencies": { ... }, "devDependencies": { ... } } Now If the developer’s system existing Node version are matched with our script then it will install dependencies and able to go further otherwise it will stop the execution and skip the dependencies installation and notify developers about this Node version issue through our script & messages. That’s it!! Now when every developer tries to execute “npm install” OR “npm start” which every developer should do in every project, they will go through our checks then and then it will go further. Thanks!!! Did you find your solution or learn something new? If so please: clap 👏 button below️ as many times as you can and share this post with others. Follow us on Medium to read more articles about Python, Angular, React, Vue, Node JS. You can leave your feedback/suggestions in the comments 💬 below. Would you like to check out our other articles? What is Progressive Web App(PWA)? Understand PWA concept in few minutes!!! How to import json file in Angular CRUD operations with Google Drive in Python using google-api-python-client Want to check Node version before project get executed using script!!! was originally published in CodeptiveSolutions on Medium, where people are continuing the conversation by highlighting and responding to this story.