I'm trying to add a local file to the zip so when the user downloads and unzips, he'll get a folder with a .dll and a config.json file:
var zip = new JSZip();
options.forEach(option => {
zip.folder("REST." + option + ".Connector")
.file("config.json", "//config for " + option)
// I want this file to be from a local directory within my project
// eg. {dir}\custom_rest_connector_repository\src\dlls\Connectors.RestConnector.dll
.file('../dlls/Connectors.RestConnector.dll', null);
});
zip.generateAsync({type:"blob"}).then(function (blob) {
FileSaver.saveAs(blob, "REST_Connectors_"
+ dateStr
+ ".zip");
});
I read through the JSZip documentation but couldn't find an example or any information whether this can actually be done.
If it can't, is there any other more robust library that does support this operation?
Found the answer to my own question using the jszip-utils
JSZipUtils.getBinaryContent("../dlls/Connectors.RestConnector.dll", function (err, data) {
if(err) {
throw err; // or handle the error
}
zip.file("../dlls/Connectors.RestConnector.dll", data, {binary:true});
});
Related
I have a node.js server (express.js) and I have a json file that I use to read and write data (simple api).
When the node.js server is stopped, that other application adds data to the json file without any problems.
When the node.js server is started that other application sees that json file as an empty file, probably
because the node.js server keeps it open.
In node.js I use fs.readFile and it closes the json file after reading, so I don't think that's the problem.
All this is happening on a local windows machine.
Has anyone had a similar problem sharing a single file with node.js and some other application?
If anyone had a direction to guide me, where to look for a solution.
Thank you for your time!
#jfriend00
As for that other application, it was written in clarion and I don't have access at the moment.
That application rarely writes data to that file.
Here's how I read and write the file:
function load(fileName, path, callback) {
let jsonPath = "";
if(fileName == "companies") {
jsonPath = __dirname + "\\..\\..\\";
} else {
jsonPath = path;
}
fs.readFile(jsonPath + fileName.toUpperCase() + '.JSON', function (err, data) {
if (err) {
if (err.code === "ENOENT") {
console.log("File '" + fileName.toUpperCase() + ".JSON' not found!");
callback([]);
return;
} else {
throw err;
}
}
callback(JSON.parse(data.toString()));
});
}
function save(fileName, path, array) {
let jsonPath = "";
if(fileName == "companies") {
jsonPath = __dirname + "\\..\\..\\";
} else {
jsonPath = path;
}
fs.writeFile(jsonPath + fileName.toUpperCase() + '.JSON', JSON.stringify(array), function (err) {
if (err) {
throw err;
}
});
}
That software which I share json with, needs nice format, not an one line data.
So, I have to added two more parameters in JSON.stringify(array, null, 2) to format data nicely wen a calling fs.writeFile method.
I totally forgot this.
This was two days of agony.
i’ve node.js app that I Need to zip all the current folder with command from
and get the zip on the root
For that I want to use the archiver npm package but I don’t understand the following:
where I put the current folder (since I want to zip all the application )
where should I put the name of the zip (the zip that should be created when execute the command)
My app have the following structure
MyApp
Node_modules
server.js
app.js
package.json
arc.js
In the arc.js I’ve put all the zip logic so I guess I need to provide zipPath (which in my case is ‘./‘)
and zip name like myZip…
I tried with the following without success, any idea ?
var fs = require('fs');
var archiver = require('archiver');
// create a file to stream archive data to.
var output = fs.createWriteStream(__dirname + '/.');
var archive = archiver('zip', {
zlib: { level: 9 } // Sets the compression level.
});
// listen for all archive data to be written
output.on('close', function() {
console.log(archive.pointer() + ' total bytes');
console.log('archiver has been finalized and the output file descriptor has closed.');
});
archive.on('warning', function(err) {
if (err.code === 'ENOENT') {
// log warning
} else {
// throw error
throw err;
}
});
// good practice to catch this error explicitly
archive.on('error', function(err) {
throw err;
});
// pipe archive data to the file
archive.pipe(output);
I need that when I open the command line like
folder->myApp-> run zip arc and will create zipped file under the current path (which is the root in this case....)
You can use the glob method, but make sure to exclude *.zip files. Otherwise the zip file itself will be part of the archive.
Here is an example:
// require modules
var fs = require('fs');
var archiver = require('archiver');
// create a file to stream archive data to.
var output = fs.createWriteStream(__dirname + '/example.zip');
var archive = archiver('zip', {
zlib: { level: 9 } // Sets the compression level.
});
// listen for all archive data to be written
output.on('close', function () {
console.log(archive.pointer() + ' total bytes');
console.log('archiver has been finalized and the output file descriptor has closed.');
});
// good practice to catch warnings (ie stat failures and other non-blocking errors)
archive.on('warning', function (err) {
if (err.code === 'ENOENT') {
// log warning
} else {
// throw error
throw err;
}
});
// good practice to catch this error explicitly
archive.on('error', function (err) {
throw err;
});
// pipe archive data to the file
archive.pipe(output);
archive.glob('**/*', { ignore: ['*.zip'] });
archive.finalize();
In the github of node-archiver there is an example folder
where I put the current folder (since I want to zip all the
application )
Example :
var file1 = __dirname + '/fixtures/file1.txt';
var file2 = __dirname + '/fixtures/file2.txt';
archive
.append(fs.createReadStream(file1), { name: 'file1.txt' })
.append(fs.createReadStream(file2), { name: 'file2.txt' })
.finalize();
Specifically about your case and directory you can use the .directory() method of archiver
where should I put the name of the zip (the zip that should be created
when execute the command)
Example :
var output = fs.createWriteStream(__dirname + '/example-output.zip');
I want to re size a uploaded image on nodejs and send it on via ftp.
Using nodejs, busboy, GraphicsMagick, and jsftp.
var uploadFile = function(dir, req, cb) {
req.busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
var imageMagick = gm.subClass({
imageMagick: true
});
console.log('Resizing file...');
console.log(filename);
imageMagick(file)
.resize(150, 150)
.stream(function(err, stdout, stderr) {
if (err)
console.log(err);
var i = [];
stdout.on('data', function(data) {
console.log('data');
i.push(data);
});
stdout.on('close', function() {
console.log('close');
var image = Buffer.concat(i);
console.log(image.length);
console.log(image);
ftp.put(image, filepath, function(hadError) {
if (!hadError) {
filename = config.one.filepath + dir + "/" + filename;
cb(null, filename);
} else {
console.log(hadError);
cb(hadError, 'Error');
}
});
});
});
});
req.pipe(req.busboy);
};
The output is now:
Resizing file...
100-0001_IMG.JPG
close
0
<Buffer >
On ftp server side I get a 0 bytes file and also never doing a cb.
I found this two questions but couln't make it work for me:
Question 1
Question 2
I guess there must be something wrong with my file I gave to gm because "data" is never written to the console.
File it self is fine since I managed to upload a unresized file to the ftp server.
I appreciate every help!
Thx
Firstly you can check your stream for errors:
stdout.on('error', function(err) {
console.log(err);
});
So if there is an error related to imageMagick it can be a mismatching of imageMagic binary and node-imagemagick library
I know this question has been asked but my mind has been blown by my inability to get this working. I am trying to upload multiple images to my server with the following code:
var formidable = require('formidable');
var fs = require('fs');
...
router.post('/add_images/:showcase_id', function(req, res){
if(!admin(req, res)) return;
var form = new formidable.IncomingForm(),
files = [];
form.uploadDir = global.__project_dirname+"/tmp";
form.on('file', function(field, file) {
console.log(file);
file.image_id = global.s4()+global.s4();
file.endPath = "/img/"+file.image_id+"."+file.type.replace("image/","");
files.push({field:field, file:file});
});
form.on('end', function() {
console.log('done');
console.log(files);
db.get("SOME SQL", function(err, image_number){
if(err){
console.log(err);
}
var db_index = 0;
if(image_number) db_index = image_number.image_order;
files.forEach(function(file, index){
try{
//this line opens the image in my computer (testing)
require("sys").exec("display " + file.file.path);
console.log(file.file.path);
fs.renameSync(file.file.path, file.file.endPath);
}catch (e){
console.log(e);
}
db.run( "SOME MORE SQL"')", function(err){
if(index == files.length)
res.redirect("/admin/gallery"+req.params.showcase_id);
});
});
});
});
form.parse(req);
});
The line that opens the image via system calls works just fine, however I continue to get:
Error: ENOENT, no such file or directory '/home/[username]/[project name]/tmp/285ef5276581cb3b8ea950a043c6ed51'
by the rename statement.
the value of file.file.path is:
/home/[username]/[project name]/tmp/285ef5276581cb3b8ea950a043c6ed51
I am so confused and have tried everything. What am I doing wrong?
Probably you get this error because the target path does not exist or you don't have write permissions.
The error you get is misleading due to a bug in nodejs, see:
https://github.com/joyent/node/issues/5287
https://github.com/joyent/node/issues/685
Consider adding:
console.log(file.file.endPath);
before the fs.renameSync call and check if the target path exist and is writable by your application
You stated form. Therefore note that Formidable doesn't work out of the box with just NodeJS. Unless you were to use something like the prompt module for input. If you are using HTML, you'll need something like Angular, React or Browserify to be able to give it access to your interface.
At work I have to repeat this same process multiple times:
Open a certain Dreamweaver file.
Look for all <p> tags and replace then with <h1> tags.
Look for all </p> and replace with </h1>.
Look for the string 'Welcome' and replace with 'goodbye'.
Look for '0:01:00' and replace with '01:00'.
Copy everything in that file.
Create a new Dreamweaver file and paste everything in the new file.
Save the new file in a given directory and call it a certain name, which can be provided as a variable.
I don't need to run the JavaScript from a browser. It can be a JavaScript file which I just double click on the desktop.
Is it possible for me to do this with JavaScript / jQuery?
There are many other programming languages that you could accomplish this task with but if you really want to use Javascript then you could do the following:
var fs = require('fs');
if(process.argv.length < 4) {
console.log('Usage: node replace.js fromFilePath toFilePath');
return;
}
from = process.argv[2];
to = process.argv[3];
fs.readFile(from, { encoding: 'utf-8' }, function (err, data) {
if (err) throw err;
console.log('successfully opened file ' + from);
var rules = {
'<p>': '<h1>',
'</p>': '</h1>',
'Welcome': 'goodbye',
'0:01:00': '01:00'
};
for(var index in rules) {
console.log('Replacing ' + index + ' with ' + rules[index] + '...');
data = data.replace(new RegExp(index, 'gi'), rules[index]);
console.log('Done');
}
console.log("Result");
console.log(data);
console.log("Writing data to " + to);
fs.writeFile(to, data, function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
});
INSTRUCTIONS
Download node.js from here
Install it
Create a file in C:\replace.js (Win) or ~/replace.js (Mac OS)
Put the code from above in replace.js
Open cmd (Ctrl+R on Win) or Terminal (on Mac OS)
Type node C:\replace.js <fileToReadFrom> <fileToSaveTo> on Win or node ~/replace.js <fileToReadFrom> <fileToSaveTo> on Mac OS
Done