I am using node.js, trying to save a file, no errors are thrown, yes the image won't save. This is how I am saving the file:
var url = 'captures/' + getFileName() + '.png';
fs.writeFile(url, base64, 'base64', function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});
With a helper to make the file names for me:
function getFileName(){
var d = new Date()
return d.getMonth()+'-'+d.getDate()+'-'+d.getYear()+'-'+d.getHours()+'-'+d.getMinutes()+d.getSeconds();
}
Anyone had trouble with this?
the problem is because this call is async and probably is loosing the context right after, I was able to fix it on my end by using fs.writeFileSync which does it synchronously. hope this helps
Add a console.log('captures/' + getFileName()) just to make sure your file name is correct. When I had this problem it turned out that I had a problem with the file path/name and node just wasn't throwing me an error to explain.
For Typescript version,
Just sharing my experience here, In my use case had a JSON file where I used to store some temporary data read it and make some changes and update it and store that updated data to same JSON file will be used for next cycle.
fs.writeFile was not throwing any error at same time it was not updating my JSON file where as JS version worked well, Then I realized that typescript made these changes in my root or src directory. Created another JSON file there.
If you want to write your file asynchronously, try using fs/promises instead of fs.
const { writeFile } = require("fs/promises");
(async () => {
await writeFile('myFile.txt', 'my content', (err) => {});
})();
writeFile from fs is void. It will execute asynchronously but not in the async-await meaning. writeFile from fs/promises returns a Promise so async-await will work as expected.
Learn more here: https://nodejs.org/api/fs.html#callback-example
There might be a permission issue.
go inside the directory that you are saving your files and then
sudo chmod 777 .
Related
I am using ssh2-sftp-client to get files from a remote server, I'm running into an issue reading and downloading these files once I get() them.
At first, I was able to use the get() method to download the file when the API was hit - I could also return the whole file contents in a console.log statement then it started returning Buffer content. I updated with this:
npm install ssh2-sftp-client#3.1.0
And now I get a ReadbleStream.
function getFile(req,res) {
sftp.connect(config).then(() => {
return sftp.get(process.env.SFTP_PATH + '/../...xml',true);
}).then((stream)=>{
const outFile = fs.createWriteStream('...xml')
stream.on('data', (c) => {
console.log(`Received ${c.length} bytes of data.`);
outFile.write(c);
res.send('ok')
});
stream.on('close', function() {
});
}).catch((err) => {
console.log(err, 'catch error');
});
};
I have the above code that returns a stream but I'm not sure how to get the file - the write() method doesn't seem to work here.
Any advice or suggestions on how I can use this library to read and download files would be greatly appreciated
First, don't use version 3.x. That version has been deprecated. The most recent version is v4.1.0 and has had significant cleanup work to fix a number of small bugs.
If all you want to do is download the files, then use the fastGet() method. It takes 2 args, source path and destination path. It is a lot faster than plain get as it does the download in parallel.
If you don't want to do that, then the get() method has a number of options. If you only pass in one arg (source) it will return a buffer. If you pass in 2 args, the second arg must be either a string (path to local file) or a writeable stream. If a writeable stream, the data will be piped into that stream.
I have tried different available solutions but file is not getting saved and nothing happens i.e, callback functions are not getting called neither success nor error.
Solution already tried.
1. Moved polyfill.js before cordova.js in index.html
2. tried writing simple text string in txt file even txt file is not getting created
3. also changed file.dataDirectory to file.cacheDirectory.
here is code sample:
var fileName = Date.now().toString() + ".csv";
var that = this;
that.file
.writeFile(that.file.cacheDirectory, fileName, csv, {
replace: true
})
.then(() => {
that.setStatus("CSV file saved as " + fileName);
})
.catch(() => {
that.setStatus("Error saving CSV file.");
});
I solved this issue. Problem was my application is in ionic 3 but when I added ionic native file plugin latest version of plugin was added (Ver. 5+). apparently there was no error no issue but on writing file no call back response was getting generated, neither success nor error. following are steps that fixed this issue for me.
Clear npm cache
add ionic native file plugin Version 4.
I would like to create a command line (or other automated) method for uploading files to priority using the Web-SDK. The best solution I have right now seems to be a simple webform activated by a python script.
Are there tools/examples for using Javascript and a file picker without opening the browser? Are there Priority-Web-SDK ports to other environments? C#, Python, etc?
Any other suggestions also welcome.
UPDATE June 14, 2020:
I was able to complete the task for this client using a combination of Javascript, Python and C#. A tangled mess indeed, but files were uploaded. I am now revisiting the task and looking for cleaner solutions.
I found a working and usable Node module to compact the program into an executable to make it a viable option for deployment.
So the question becomes more focused => creating the input for uploadDataUrl() or uploadFile() without a browser form.
You run node locally and use priority SDK.
*As long as you work in an environment that is capable to render JS.
You can send files through the function uploadFile.
The data inside the file object need to be written as 64 base file.
This nodejs script will upload a file to Priority. Make sure that fetch-base64 is npm installed:
"use strict";
const priority = require('priority-web-sdk');
const fetch = require('fetch-base64');
const configuration = {...};
async function uploadFile(formName, zoomVal, filepath, filename) {
try {
await priority.login(configuration);
let form = await priority.formStartEx(formName, null, null, null, 1, {zoomValue: zoomVal});
await form.startSubForm("EXTFILES", null ,null);
let data = await fetch.local(filepath + '/' + filename);
let f = await form.uploadDataUrl(data[0], filename.match(/\..+$/i)[0], () => {});
await form.fieldUpdate("EXTFILENAME", f.file); // Path
await form.fieldUpdate("EXTFILEDES", filename); // Name
await form.saveRow(0);
} catch(err) {
console.log('Something bad happened:');
console.dir(err);
}
}
uploadFile('AINVOICES', 'T9679', 'C:/my/path', 'a.pdf');
If i have the code below how can i edit the specific file and make the right corrections?
var p4 = require('C:/Program Files/nodejs/node_modules/p4');
var File = process.argv[2];
p4.edit(File, function(err, data) {
if (err) {
console.error(err.message);
}
console.log(data);
});
Your code looks correct to open the file for edit. If that returns any errors when you run it, you should post those here, but I'll assume that it returns a success message ("(file) opened for edit").
Opening the file for edit means that it is made writable on the local filesystem (i.e. the one where this code is running -- the file is the one you passed as an argument to the edit command). To actually modify the file you can use any other function at your disposal.
i am trying to upload zip file and then i have to extract it in server side and also i have to handle error while extracting that zip file.to extract i am trying like this
var zip = new AdmZip(x);
zip.extractAllTo('target path');
the extractAllTo not contain call back function ,if it is contain that i can handle err easily so let me know how to handle err while extracting zip file.
i am creating one tmp folder and after upload file and then i keep that uploaded file into tmp folder and then i am storing that uploaded file into original folder and i will take that path to store db(mongodb).After stored data i got stored result in callback function within that callback function i have tried to remove that tmp folder but i could not remove it.i have tired to remove without that data stored callback function it is working . what mistake i did.how to resolve it.i have tried like this
db.save({'filepath':'xxxxx'},function(err,data)
{
if(data)
{
fs.rmdir('xxxx/xxxxx',function(err)
{
if(err)
{
console.log('err')
}else
{
console.log('removed');
}
});
}
});
i am always received in console that err.
After looking in the code from adm-zip, the only way is to embed extraction in a try {} catch statement:
var zip = new AdmZip(x);
try {
zip.extractAllTo('target path');
} catch ( e ) {
console.log( 'Caught exception: ', e );
}
It looks like your library is synchronous, which is why it doesn't use callbacks. If you are uploading a zip file to a server, synchronous calls will halt your entire server for all clients and thus you should switch to an asynchronous library to do this work. FYI for the synchronous version, to handle errors, you would use a try/catch structure as the exceptions thrown are in a single execution stack.