Box API upload files to admin account instead of APP - box-api

Hey I use the Box API and I successfull to upload my files but they are stored at the app storage folder. If you would go to the admin-console and then click the folder Icon you can see the admin folder and then the folder of the created app. How can I change the path that every upload will go to the admin folder that if I relog to box.com I would see all my files in the home folder instead of going to the admin-console every time?

This should work.
var client = sdk.getAppAuthClient('enterprise', ENTERPRISE_ID);
//filter_term == admin to share the folder with
client.enterprise.getUsers({filter_term: 'ken.domen#nike.com'}, function(err, users) {
var userId = users.entries[0].id;
client.folders.create('0', 'New Folder', function(err, newFolder) {
client.collaborations.createWithUserID(userId, newFolder.id, client.collaborationRoles.VIEWER, function(err, collaboration) {
console.log(err);
var fileData = fs.createReadStream('/users/kdomen/Downloads/test.txt')
client.files.uploadFile(newFolder.id, 'test.txt', fileData, function(err, file) {
if (err){
console.log('err: ' + err);
}
else{
console.log('file uploaded: ' + file);
}
});
});
});
});

Related

how to create folder and upload images in ipfs

https://proto.school/#/mutable-file-system
I have gone through this link but don’t know how to do same thing in node.js
I have added 'hello' word into the IPFS network and its working fine and also i have used image to upload into ipfs but i want to know how can i create folder in ipfs network and upload images into that folder
So my problem is that how to create the folder and upload picture into that folder.
Here is my code.
const addFile = async () => {
//const Added = await ipfs.add('hello');
const fsReadImgData = fs.readFileSync('image1.jpg');
var ipfsSave = await ipfs.add({
path:image1.jpg,
content: fsReadImgData
});
return fsReadImgData;
}
const fileHash = await addFile();
First read file into a buffer (or replace with however you're getting the image data:
const imgdata = fs.readFileSync('/yourfile.jpg');
Regular IPFS files method (immutable, you do not expect to update these):
let added = await ipfs.add({
path: 'images/yourfile.jpg',
content: imgdata
}, { wrapWithDirectory: true })
Mutable filesystem method (you expect to update and change the files):
await ipfs.files.mkdir('/images')
await ipfs.files.write(
'/images/yourfile.jpg',
imgdata,
{create: true})

How to check if an HTML file is in a given directory, and then open that file with the referenced CSS and JS files within same directory

For my homework problem, I need to check if a file exists in a certain
directory "public", and then if it does, open it up through the
localhost in a browser. I wanted to use a function to check if the file
exists in directory, and then if true, send the file path to another function that'll open the file. This is all on my server.js file, and the HTML file I want to open along with the CSS and JS for the HTML file are all in my public directory.
This is using node.js. I need to run node server.js in the console, and then go to my localhost in a browser and see the displayed webpage with style and functionality. I've tried using fs.access and fs.existsSync. We are not allowed to use express on this assignment.
var http = require('http');
var fs = require('fs');
http.createServer(function(req, res) {
var filepath = 'public' + req.url;
if (req.url == '/index.html' || req.url == '/') {
fs.access(filepath);
}
}).listen(3000);
console.log("Server running on Port 3000...");
fs.access(filepath, (access) =>{
if (access) {
res.statusCode = 200;
sendFile(filepath, res);
}
else {
res.statusCode = 404;
sendFile('public/404.html', res);
}
});
function sendFile(path, res) {
fs.readFile(path, "utf8", function(data){
res.end(data);
});
}
I'm getting an error that says filepath is not defined (when I use it in the parameters when I call fs.access.
fs requires paths with a leading slash to work, so instead of var filepath = 'public' + req.url;, try
var filepath = '/public' + req.url;

How to upload a file from pre-defined location in pc onto a webpage? without user intervension

I can have the user upload a file on a webpage using <input type='file' accept='text/plain' onchange='ReadTheTextfile(event)'>.
and then use javascript: FileReader,
reader.readAsText(event.target.files[0]); etc
but I already know that I want to read a file, which I already uploaded to the webserver.
How can I determine by myself which file I want to upload / read ? XMLHttpRequest ?
I don't want to read a file from the user's pc.
I want to read a file from the server, where my html files are also hosted.
You can retrive it via ajax call as follows.
function getFileFromServer(url, doneCallback) {
var xhr;
xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleStateChange;
xhr.open("GET", url, true);
xhr.send();
function handleStateChange() {
if (xhr.readyState === 4) {
doneCallback(xhr.status == 200 ? xhr.responseText : null);
}
}
}
getFileFromServer("path/to/file", function(text) {
if (text === null) {
// An error occurred
}
else {
// `text` is the file text
}
});
Reference - https://stackoverflow.com/a/13329900/9640177

NodeJS reload page but don't send user data again [duplicate]

This question already has answers here:
How to prevent form resubmission when page is refreshed (F5 / CTRL+R)
(21 answers)
Closed 4 years ago.
I have a Node Js local server and several identical html pages. On every page I save some user data input fields saved simply on a text file. My problem is that if the users refresh the page the data from the previous html page is send again and again saved on the text file. Is there a way to prevent this?
var fs = require('fs');
const log=require('simple-node-logger').createSimpleLogger();
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
var port = process.env.PORT || 8000;
app.use(express.static(__dirname + '/server'));
app.use(express.static(__dirname + "/public"));
app.use('/images', express.static(__dirname +'/images'));
app.listen(port, function(){
console.log('server is running on ' + port);
});
app.get('/', function(req, res){
res.sendfile('intro.html');
});
app.post('/userID', function(req, res){
//save the userID on a text file
var userID= req.body.userID + ';';
var data = fs.appendFileSync('temporary/userID.txt', userID, 'utf8');
return res.sendfile('main.html');
});
app.post('/submit', function(req, res){
res.sendfile('main2.html');
});
Furthermore, I have also a refresh button that does the same as the browser refresh button. I s there a way to avoid the same problem?
<button>Reset</button>
and its JavaScript:
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('button').addEventListener('click', clickHandler);
});
function clickHandler(element) {
location.reload();
}
Thank you in advance!
You can use fs.readFile and check if that file contain that userId
If that is not present then append or else dont append
fs.readFile('temporary/userID.txt', function (err, fileData) {
if (err) throw err;
if(fileData.indexOf(userID) == -1){
var data = fs.appendFileSync('temporary/userID.txt', userID, 'utf8');
}
});
So, the code will be:
app.post('/userID', function(req, res){
//save the userID on a text file
var userID= req.body.userID + ';';
fs.readFile('temporary/userID.txt', function (err, fileData) {
if (err) throw err;
if(fileData.indexOf(userID) == -1){
var data = fs.appendFileSync('temporary/userID.txt', userID, 'utf8');
}
});
return res.sendfile('main.html');
});

NodeJS MySQL Query in .forEach() seems to not execute / execute only once

I am trying to write a little script that reads an xml-file and then imports the data I fetch into a MySQL-Database. The fetching works fine, but the inserting is a problem. I've worked with the .forEach to stay asnyc which helped me a lot and worked fine until I needed to insert the Data. When I tried to execute the "INSERT"-Query outside of the 'Loops' everything works fine, but as soon as I try to execute it inside of one it just inserts everything once and then stops. Also the console.log() message inside the connection.query() doesn't get executed, even though no error gets thrown.
This is my code:
console.log("Running import!");
//Import necessary modules
var fs = require("fs");
var config = require("./config");
var mysql = require("mysql");
var path = require("path");
var xml2js = require("xml2js");
var parser = new xml2js.Parser();
var connection = mysql.createConnection({
host : config.mysql.host,
user : config.mysql.user,
password : config.mysql.password,
database : config.mysql.db
});
connection.connect(function(err) {
if (err) { //throw error
console.error(err.stack);
throw err;
}else{
console.log("Succesfully connected to the database!");
// Get Folders in Folder and iterate through every of them
var dirs = getDirectories(config.misc.path);
dirs.forEach(function(dir, index){
var file = config.misc.path + "\\" + dir + "\\" + config.misc.xml_name;
// read xml file of that directory
fs.readFile(file, function(err, data){
parser.parseString(data, function(err, json){
if(err) throw err;
json.resultset.forecast.forEach(function(forecast, index){
forecast.parking_house.forEach(function(ph, index){
var ph_id = ph["$"].id;
ph.estimate.forEach(function(estimate, index){
var value = estimate.value[0]["_"];
var time = estimate.timestamp[0]["_"];
//console.log(time);
connection.query("INSERT INTO lb_data.estimates VALUES (DEFAULT,'23:00:00', 213, 44);", function(error, results, fields){
if(error) throw error;
//Printing %
var perc = (index / dirs.length * 100);
console.log("Scanned and imported " + Math.round(perc) + "% of the files");
});
});
});
});
});
});
});
}
});
/**
* Gets the direcotries in a directory
* #param {string} srcpath the source path of the directory you want to scan
* #return {void}
*/
function getDirectories (srcpath) {
return fs.readdirSync(srcpath)
.filter(file => fs.statSync(path.join(srcpath, file)).isDirectory())
}
Already a big thanks in advance!
PS: Be ensured that the data in config.json is fine, I've tested that outside the loop, so that is not the problem ....