Find a file in React - reactjs

How to search a specific named file in a folder using React ?
My file name is like below
var filename = window.location.hostname ;
Now I would like to search the file like below
if(require('../public/service/filename.json')) {
//do something
}
else {
//do something
}

You can use following way:
const checkFileExist = (path) => {
try {
return require(`${path}`);
} catch (err) {
return null;
}
};
and use it on your component
if(checkFileExist('../public/service/filename.json') === null) {
// something
} else {
// something
}

Related

Attach files to record in Netsuite

I am transferring attachments from Zoho to Netsuite. But facing problems while attaching it to opportunity or any other object. I have already uploaded the file to the file cabinet in netsuite and tried to bind it with the records notes. But that doesn't work. It only adds the note to the record but no sign of any file in the file option.
Thank you.
enter image description here
You would use the record.attach function. You would need the internal id of the file and of the transaction. In SS1 (using nlapiAttachRecord) it was important to list the file arguments first. The SS2 syntax makes that clearer:
record.attach({
record:{
type:'file',
id:fileid
},
to:{
type:'transaction',
id:transactionid
}
});
/**
* #NApiVersion 2.1
* #NScriptType MapReduceScript
* #NModuleScope SameAccount
*/
/**
* In this I am using Map Reduce script to process & attach multiple files from
* FileCabinet of NetSuite. So that it never goes out of governance.
/
define(['N/record','N/query'],
(record,query) => {
const getInputData = (getInputDataContext) => {
try
{
/**
* Query for getting transaction ID & other header detail of record.
*/
let transQuery = "SELECT custrecord_rf_tid as tid, custrecord_rf_fid as fid, id FROM customrecord_rflink where custrecord_rf_comp <> 'T' and custrecord_rf_type = 11";
let transQueryResult = runSuiteQuery(transQuery);
if(transQueryResult.length > 0){
log.debug("Count of record left to process--->", transQueryResult.length);
return transQueryResult;
}else{ //Incase where no transaction was left to transform.
log.debug({title: "No Remaining Transaction!"});
return 1;
}
}
catch (e)
{
log.error({title: "Error inside getinput data.", details: [e.message,e.stack]});
}
}
const map = (mapContext) => {
try{
let mapData = JSON.parse(mapContext.value);
log.debug({title: "mapData after parse", details: mapData});
let staginRecId = Number(mapData.id);
let fileId = Number(mapData.fid);
let billId = Number(mapData.tid);
let outputVal = attachfile('file',fileId, 'inventoryadjustment', billId);
let staginRec;
if(outputVal === true){
staginRec = record.submitFields({
type: 'customrecord_rflink',
id: staginRecId,
values: {
'custrecord_rf_comp': true
}
});
log.debug("record saved with id-->", staginRecId);
}else{
log.debug("record saving failed with id-->", staginRecId);
}
}
catch(e){
log.error({title: "Error in Map", details: [e.message,e.stack]});
}
}
const reduce = (reduceContext) => {
}
const summarize = (summarizeContext) => {
log.debug('Summarize completed');
}
function runSuiteQuery(queryString) {
log.debug("Query", queryString);
let resultSet = query.runSuiteQL({
query: queryString
});
log.debug("Query wise Data", resultSet.asMappedResults());
if(resultSet && resultSet.results && resultSet.results.length > 0) {
return resultSet.asMappedResults();
} else {
return [];
}
}
function attachfile(recType, recId, recTypeTo, recIdTo) {
record.attach({
record: {
type: recType,
id: recId
},
to: {
type: recTypeTo,
id: recIdTo
}
});
return true;
}
return {getInputData,map,reduce,summarize};
});

Check if asset exists

Is there any way to check if a asset file exists in Flutter before try to load the data?
For now I have the following:
String data;
try {
data = await rootBundle
.loadString('path/to/file.json');
} catch (Exception) {
print('file not found');
}
The problem is, that I have to check for file 1, if this does not exits I have to check for a fallback file (file 2) and if this does also not exist I load a third file.
My complete code would look like this:
try{
//load file 1
} catch (..) {
//file 1 not found
//load file 2
} catch (...) {
//file 2 not found
//load file 3
}
That looks very ugly to me, but I have no better idea...
AssetBundle (as returned by rootBundle) abstracts over different ways of loading assets (local file, network) and there is no general way of checking if it exists.
You can easily wrap your loading code so that it becomes less "ugly".
Future myLoadAsset(String path) async {
try {
return await rootBundle.loadString(path);
} catch(_) {
return null;
}
}
var assetPaths = ['file1path', 'file2path', 'file3path'];
var asset;
for(var assetPath in assetPaths) {
asset = await myLoadAsset(assetPath);
if(asset != null) {
break;
}
}
if(asset == null) {
throw "Asset and fallback assets couldn't be loaded";
}
I believe a better version is the one without the need to try/catch:
import 'dart:convert';
import 'package:flutter/services.dart';
Future<bool> isLocalAsset(final String assetPath) async {
final encoded = utf8.encoder.convert(Uri(path: Uri.encodeFull(assetPath)).path);
final asset = await ServicesBinding.instance.defaultBinaryMessenger.send('flutter/assets', encoded.buffer.asByteData());
return asset != null;
}

Function Download in Yii2

public function actionUnduh($id) {
$download = PstkIdentifikasi::findOne($id);
$path = Yii::getAlias('../web/bukti/') . $download->bukti;
if (file_exists($path)) {
//return \Yii::$app->response->sendFile($download->pre_paper,#file_get_contents($path));
return Yii::$app->response->sendFile($path);
}
}
I need to download file from folder web/bukti, the code not error but the code doesn't work, Anyone can help me :(
public function actionUnduh($id)
{
$download = PstkIdentifikasi::findOne($id);
$path = Yii::getAlias('#webroot').'/bukti/'.$download->bukti;
if (file_exists($path)) {
return Yii::$app->response->sendFile($path, 'File name here');
}
}
Refer below:
Yii2 Aliases
Yii2 sendFile()
Firstly you can write an action in SiteController.php like this:
public function actionDownload()
{
$file=Yii::$app->request->get('file');
$path=Yii::$app->request->get('path');
$root=Yii::getAlias('#webroot').$path.$file;
if (file_exists($root)) {
return Yii::$app->response->sendFile($root);
} else {
throw new \yii\web\NotFoundHttpException("{$file} is not found!");
}
}
then you can call this function anywhere:
Yii::$app->urlManager->createUrl(['site/download','path'=>'/upload/files/','file'=>'filename.pdf'])
Be careful your files must be in this directory:
"backend/web/upload/files/filename.pdf"
or
"frontend/web/upload/files/filename.pdf"

NodeJS callback: How to make the call wait for mongodb query result

I have a registration dialog where when the user enters username and password I need to check the DB whether the user is present
or not. But when I am validation for the same my call does not hold back until I get the results from the server.
After searching for a while I got to know about callbacks. So I have added a call back inside this.isUser method.
And it is successful. But now doRegistration method is not synchronous with the isUser method.
How to make all my calls synchronous?
this.doRegistration = function(uname, pwd, confirmPwd) {
if(this.isUser(uname)) {
return "USER_EXISTS";
} else {
saveUser(uname, pwd);
return "SUCCESS";
}
};
this.isUser = function(username) {
var users = new Array();
getAllUsers('param', function(response) {
users = response;
console.log(users.length);
for(i = 0; i < users.length; i++) {
if(users[i].username === username) {
return true;
}
}
return false;
});
};
function getAllUsers(param, callback) {
loginFactory.AllUsers.query(function(response) {
if(response != undefined && response.length > 0) {
callback(response);
}
});
}
You may rewrite the code like following:
this.doRegistration = function(uname, pwd, confirmPwd, callBack) {
this.isUser(uname,function(flag) {
if(flag){
callBack("USER_EXISTS");
}
else {
saveUser(uname, pwd, function(err,result){
if(err){
callBack("SAVING_FAILED");
}
else {
callBack("SUCCESS");
}
});
}
});
};
this.isUser = function(username,callBack) {
var users = new Array();
getAllUsers('param', function(response) {
users = response;
console.log(users.length);
for(i = 0; i < users.length; i++) {
if(users[i].username === username) {
callBack(true);
}
}
callBack(false);
});
};
function saveUser(userName, pwd, callBack){
//code to save user
//chek for error in saving
if(err){
callBack(err,null)
}
else {
callBack(null, "success")
}
}
function getAllUsers(param, callback) {
loginFactory.AllUsers.query(function(response) {
if(response != undefined && response.length > 0) {
callback(response);
}
});
}
You may also define saveUser as a function with callback. Here it wont wait for saveUser method to complete.

Recursively Read all files and folder structure using Cordova

IS there any way to read the files and folder structure recursively starting from root.
The scope here is to scan all the files present in the directory along with there directory ,sub-directory using cordova
Take a look at the answer here: https://stackoverflow.com/a/29905718/346550. This is using the cordova file plugin.
scan : function(url,fileType,callback)
{
var fileTypeCollection = [];
var defer = $q.defer();
url.forEach(function(element, index)
{
//requestLocalFileSystemURL
log(element);
window.resolveLocalFileSystemURL(element,onRequestFileSystem, fail);
log("Ends resolve");
});
function onRequestFileSystem(fileSystem)
{
var directoryReader = fileSystem.createReader();
directoryReader.readEntries(onReadEntries,fail);
} /*onRequestFile Ends*/
function onReadEntries(entries)
{
if(entries.length==0)
{
log("Entries Length....Resolving");
defer.resolve(fileTypeCollection);
}
else
{
entries.forEach( function(element, index)
{
if (element.isDirectory === true)
{
// Recursive -- call back into this subdirectory
onRequestFileSystem(element);
}
if(element.isFile == true)
{
fileType.forEach(function(type)
{
if(element.name.indexOf(type) != -1)
{
fileTypeCollection.push(element);
}
});
} /*is File ENds*/
}); /*Entries For Each Ends*/
}
} /*OnRead Ends*/
function fail(resp)
{
log(resp);
defer.reject();
} /*Fail Ends*/
return defer.promise;
} //Scan Function Ends
have a look.This plugin can scan files based on filetype
https://github.com/siddmegadeth/Cordova-Media-Scanner

Resources