Circuit SDK File Upload Example not working on node 8 - circuit-sdk

I am currently playing with the file upload functionality.
Using the example from: https://github.com/circuit/node-sdk-example/blob/master/index.js
var FileAPI = require('file-api');
var File = FileAPI.File;
//*********************************************************************
//* getFiles -- helper
//*********************************************************************
this.getFiles = function(path) {
var files = [];
var fileNames = fs.readdirSync(path);
fileNames.forEach(function (element) {
var file = new File(path + element);
files.push(file);
});
logger.debug('[APP]: getFiles' + files);
return files;
};
//*********************************************************************
//* Circuit - Post Logs
//*********************************************************************
this.postLog = function () {
logger.info('[APP]: Log Message will be posted');
//Get post content from File
var text = fs.readFileSync(config.log_message,'utf8')
logger.info('[APP]: Log Message extracted :', text);
//Get files from folder
var files = self.getFiles(config.log_folder);
var message = {
content: text,
attachments: [files]
};
return client.addTextItem(config.conversationID, message);
};
Could it be that it is not supported in the latest Node version?
I get the following error message:
TypeError: mime.lookup is not a function\n
at new File (/GIT/logToCircuit/node_modules/File/File.js:37:35)\n
at /GIT/logToCircuit/app.js:109:24\n
at Array.forEach (native)\n
at LogToCircuit.getFiles (/GIT/logToCircuit/app.js:108:19)\n
at LogToCircuit.postLog (/GIT/logToCircuit/app.js:128:26)\n
at /GIT/logToCircuit/app.js:84:18\n
at /GIT/logToCircuit/node_modules/circuit-sdk/circuit.js:18119:25\n
at Array.forEach (native)\n
at BaseEventTarget.dispatch (/GIT/logToCircuit/node_modules/circuit-sdk/circuit.js:18117:34)\n
at /GIT/logToCircuit/node_modules/circuit-sdk/circuit.js:49132:27","time":"2018-06-24T11:52:28.631Z","v":0}

mime.lookup was renamed to mime.getType see https://www.npmjs.com/package/mime.
What version of file-api are you including? The node-sdk-example includes git://github.com/voodoohop/file-api.git for exactly this reason. See https://github.com/node-file-api/file-api/issues/4.

Related

Suitescript error: TypeError: Cannot set property "JSZipSync" of undefined

I have the following script where I am getting an error message:
org.mozilla.javascript.EcmaError: TypeError: Cannot set property
"JSZipSync" of undefined to
"org.mozilla.javascript.InterpretedFunction#6e57e155"
(/SuiteScripts/Suitelet to Excel.js#17(eval)#2)
According to Netsuite support, there are no issues with the script and they are not getting this error message
/**
*#NApiVersion 2.x
*#NScriptType Suitelet
*/
define(["N/search", "N/file", "N/https"], function (search, file, https) {
function onRequest(context) {
// Load the xlsx library from the CDN
var response = https.get({
url: "https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.0/xlsx.full.min.js",
});
var script = response.body;
eval(script);
// Replace this with the ID of the saved search you want to run
var searchId = "customsearch_my_saved_search";
// Run the search and get the results
var searchResult = search.load({
id: searchId,
});
var searchRows = searchResult.run().getRange({
start: 0,
end: 1000,
});
// Create an array to hold the data for the Excel file
var data = [];
// Add the column names as the first row
var columnNames = [];
searchResult.columns.forEach(function (column) {
columnNames.push(column.label);
});
data.push(columnNames);
// Add the search results to the data array
searchRows.forEach(function (row) {
var rowData = [];
searchResult.columns.forEach(function (column) {
rowData.push(
row.getValue({
name: column.name,
})
);
});
data.push(rowData);
});
// Create the Excel file
var ws = XLSX.utils.aoa_to_sheet(data);
var wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
var binaryData = XLSX.write(wb, {
type: "binary",
bookType: "xlsx",
});
var fileName = "search_results.xlsx";
var folderId = -4; // -4 represents the "Home" folder in the file cabinet
var file = file.create({
name: fileName,
fileType: file.Type.EXCEL,
contents: binaryData,
folder: folderId,
});
// Send the file as a response to the user
context.response.writeFile({
file: file,
isInline: true,
});
});
}
return {
onRequest: onRequest,
};
});
I can't tell where I am going wrong?
The JSZipSync is a function in the xlsx.full.min.js library which I believe I have loaded correctly.
I have also tried storing this file in the filing cabinet and referencing that instead of a link to the CDN website.
The same error message is generated in both cases

how to upload a file using autoit in protractor

I tried the code below but it isn't working. Can someone help me understand how to upload a file using autoit in protractor?
var path = require('path');
var file = "../Snaptrude/plans/"+filepath+"";
console.log('file path',file)
var filePath = path.resolve(__dirname, file);
// browser.sleep(3000);
element(by.css('input[type="file"]')).sendKeys(filePath);
var path = require('path');
var appRoot = require('app-root-path');
var uploadFile = appRoot + '/path of the file which you want to upload';
var deferred = protractor.promise.defer();
var control = element(by.xpath('you need to take the xpath of uploaded file'));
control.getText().then(function(text) {
if (text == 'filename') {
enter code hereconsole.log("success");
}
without using autoit you can upload the file using above way, if you are work on any web application.

Titanium - Get image file from filesystem on Android

I have a problem getting an image from filesystem. On iOS works fine.
First of all, I save a remote image in the filesystem with this function:
img.imagen = url from the remote image (e.g. http://onesite.es/img2.jpeg)
function descargarImagen(img, callback){
var path = img.imagen;
var filename = path.split("/").pop();
var xhr = Titanium.Network.createHTTPClient({
onload: function() {
// first, grab a "handle" to the file where you'll store the downloaded data
var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, filename);
f.write(this.responseData); // write to the file
Ti.API.debug("-- Imagen guardada: " + f.nativePath);
callback({path: f.nativePath});
},
timeout: 10000
});
xhr.open('GET', path);
xhr.send();
}
Now, I want to share this image creating an Android Intent:
args.image = f.nativePath(in the previous function)
var intent = null;
var intentType = null;
intent = Ti.Android.createIntent({
action: Ti.Android.ACTION_SEND
});
// add text status
if (args.status){
intent.putExtra(Ti.Android.EXTRA_TEXT, args.status);
}
// change type according to the content
if (args.image){
intent.type = "image/*";
intent.putExtraUri(Ti.Android.EXTRA_STREAM, args.image);
}else{
intent.type = "text/plain";
intent.addCategory(Ti.Android.CATEGORY_DEFAULT);
}
// launch intent
Ti.Android.currentActivity.startActivity(Ti.Android.createIntentChooser(intent, args.androidDialogTitle));
What I'm doing wrong?

Example code to use GridFS using mongoskin to upload file from form

I am using mongoskin to connect mongodb in my project. Now I have requirement to use GridFs to upload images, audio etc. I have one HTML form to upload these files.
I tried to find out example code to upload file using mongoskin however could't find any good one.
Please help.
After spending many hours; I am able to use mongoskin to upload file to Gridfs. Not sure if this is perfect code however sharing it here because I couldn't find any single working code on searching Google :-)
https://github.com/dilipkumar2k6/gridfs-mongoskin
var DBModule = require('./DBModule.js');
var Grid = require('gridfs-stream');
var mongoskin = require('mongoskin');
//Upload file to server and also update the database
exports.uploadContent = function (req, res) {
console.log('Calling uploadFile inside FileUploadService');
req.pipe(req.busboy);
req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
console.log('uploadFile after busboy fieldname: ' + fieldname + ", file : " + file + ", filename : " + filename);
// make sure the db instance is open before passing into `Grid`
var gfs = Grid(DBModule.db, mongoskin);
//Get metadata var host = req.headers['host'];
var metadata = {contentType: mimetype};
var writestream = gfs.createWriteStream({filename: filename, metadata: metadata});
file.pipe(writestream);
writestream.on('close', function (file) {
// return URL to acces the uploaded content
var path = "contents/" + file._id;
res.json({"path": path});
});
writestream.on('error', function (err) {
log.error({err: err}, 'Failed to upload file to database');
res.status(constants.HTTP_CODE_INTERNAL_SERVER_ERROR);
res.json({error: err});
});
});
};
//view file from database
exports.previewContent = function (req, res) {
var contentId = new DBModule.BSON.ObjectID(req.params.contentid);
console.log('Calling previewFile inside FileUploadService for content id ' + contentId);
var gs = DBModule.db.gridStore(contentId, 'r');
gs.read(function (err, data) {
if (!err) {
//res.setHeader('Content-Type', metadata.contentType);
res.end(data);
} else {
log.error({err: err}, 'Failed to read the content for id ' + contentId);
res.status(constants.HTTP_CODE_INTERNAL_SERVER_ERROR);
res.json({error: err});
}
});
};
Try this to store the data using gridfs (by default uses mongoskin). It worked for me.
var ObjectID = require('mongodb').ObjectID,
GridStore = require('mongodb').GridStore;
exports.saveMedia = function(db, media, next) {
console.log(media)
db.open(function (err, db) {
// Create a file and open it
var gridStore = new GridStore(db, new ObjectID(), "w");
gridStore.open(function (err, gridStore) {
// Write some content to the file
gridStore.write(new Buffer(media), function (err, gridStore) {
// Flush the file to db
gridStore.close(function (err, fileData)
//returns filename
next(null, fileData)
});
});
});
});
}

How can I save a zip file to local storage in a win8 app using JSZip?

I'm able to create the JSZip object in my code, but I'm having trouble saving that to local storage in my windows 8 app. The examples I'm able to find set the browser's location.href to trigger a download, which isn't really an option for me.
I've included my code below. The zip file I end up with is invalid and can't be opened. Any help would be appreciated.
For reference: JSZip
function _zipTest() {
var dbFile = null;
var zipData = null;
Windows.Storage.StorageFile.getFileFromPathAsync(config.db.path)
.then(function (file) {
dbFile = file;
return Windows.Storage.FileIO.readBufferAsync(file);
})
.then(function (buffer) {
//Read the database file into a byte array and create a new zip file
zipData = new Uint8Array(buffer.length);
var dataReader = Windows.Storage.Streams.DataReader.fromBuffer(buffer);
dataReader.readBytes(zipData);
dataReader.close();
var localFolder = Windows.Storage.ApplicationData.current.localFolder;
return localFolder.createFileAsync(dbFile.displayName.concat('.zip'), Windows.Storage.CreationCollisionOption.replaceExisting)
})
.then(function (file) {
//Write the zip data to the new zip file
var zip = new JSZip();
zip.file(dbFile.displayName, zipData);
var content = zip.generate();
return Windows.Storage.FileIO.writeTextAsync(file, content);
});
}
you can do something on these lines. This code seem to generate valid .zip file in the temp folder.
var zip = new JSZip();
var storage = Windows.Storage;
storage.StorageFile.getFileFromApplicationUriAsync(new Windows.Foundation.Uri('ms-appx:///images/logo.png')).then(function ongetfile(file)
{
var blob = MSApp.createFileFromStorageFile(file);
var url = URL.createObjectURL(blob, { oneTimeOnly: true });
return WinJS.xhr({ url: url, responseType: 'arraybuffer' });
}).then(function onreadbuffer(req)
{
var b = req.response;
zip.file('logo.png', b);
return storage.ApplicationData.current.temporaryFolder.createFileAsync('a.zip', storage.CreationCollisionOption.replaceExisting);
}).then(function onnewfile(out)
{
var content = zip.generate({ type: 'uint8array' });
return storage.FileIO.writeBytesAsync(out, content);
}).then(null, function onerror(error)
{
// TODO: error handling
});