I want zip a folder which contains few files. I am using zip-folder and 7zip-min modules they are working fine. But, I would like to add some parameters to it, like compression level and directory size and so on.
If it is not possible with this module, Can anyone provide other suggestions?
Here is my code :
Example 1-
const zipFolder = require('zip-folder');
zipFolder('./folder', './compressed.zip', function(err) {
if(err) {
console.log('something went wrong!', err);
} else {
console.log('done with compressing');
}
});
Example 2-
const _7z = require('7zip-min');
let pack = _7z.pack('./folder', './compressed.7z', err => {
console.log('I am done with compressing')
});
Related
I am building an app with Electron in which there are some executables which run just fine when running npm start from terminal using the child-process in Javascript. However when packaging it with electron-builder my app just cannot find the executables. I have read many related posts and none answer my question.
The solution here https://github.com/sindresorhus/fix-path does not resolve my issue.
Here is my code
function updateCourses(platform){
const fixPath = require('fix-path');
alert(process.env.PATH);
fixPath(); //This is the package but does not resolve my issue
alert(process.env.PATH);
const path=require('path');
var fs = require("fs");
var mysql=require("mysql");
// /Applications/mooc-platform.app/
alert(__dirname);
const { exec } = require('child_process');
var run="./../../Users/thanasis/Desktop/mooc-platform\ Mac/scrape_"+String(platform);
exec(run,(error, stdout, stderr) => {
if (error) {
alert(`exec error: ${error}`);
alert(`Something wrong happened: ${stdout}`);
alert(`stderr: ${stderr}`);
return;
}
else{
alert(platform+" courses downloaded");
alert("Updating database");
var con=mysql.createConnection({
host: "localhost",
user: "root",
password: "simple1234",
database: "moocs"
});
var v=false;
con.connect(function(err){
if(err) throw err;
console.log("Connected!");
platform=String(platform);
var num = fs.readFileSync("../../Users/thanasis/Desktop/mooc-platform\ Mac/courses/"+platform+"/numofcourses.txt");
num=parseInt(num,10);
let plat=platform;
for(i=0; i<num; i++){
pth="../../Users/thanasis/Desktop/mooc-platform\ Mac/courses/"+platform+"/course"+i.toString()+".json";
var content = fs.readFileSync(pth);
var object = JSON.parse(content);
String.prototype.setCharAt = function(index,chr) {
if(index > this.length-1) return str;
return this.substr(0,index) + chr + this.substr(index+1);
}
var ti=String(object.title);
ti=ti.replace(/'/g,'i');
sql="INSERT INTO courses (name) VALUES('"+ti+"') ON DUPLICATE KEY UPDATE hits=0";
con.query(sql,function(err,result){
if(err) throw err;
console.log(result);
});
// con.query('DELETE FROM courses',function(err,result){
// if(err) throw(err);
// console.log(result);
// });
}
v=true;
con.end(function(err,result){
if(err) throw err;
if(!alert("Updated")){
window.location.href="load_courses.html";
}
});
});
}
});
}
Optimally this would run from the applications folder (in Macos) with no issue.
Any help would be greatly appreciated.
Assuming you are packaging your app as asar:
All your paths are relative to your file. So the moment this file changes its location the path won't work anymore.
Packing with asar changes
C:\myApp\scripts\main.js
to
C:\myApp\resources\myAppName.asar\scripts\main.js
so your files cannot be found from there.
There are a couple of options. For example:
Putting all of your executables and text files inside the asar.
Upside: you can distribute them with your app. Downside: App might
get big and this will not work with all executable files, as some may
need dependencies on their own.
Determine somehow an absolute path on the current machine (I have no
idea of macOS. On Windows I read the registry and extract the path I
need from there.)
Provide different paths if packed or not via e.g.
electron-is-running-in-asarpackage.
Would like to write data into specific folder using writefile in node js.
I have seen couple of questions in stackoverflow regarding this but none of them worked for me .
For example :
fs.writeFile('./niktoResults/result.txt', 'This is my text', function (err) {
if (err) throw err;
console.log('Results Received');
});
This throws an error "NO SUCH FILE OR DIRECTORY"
Is there any alternative for writing data into specific folder node js ???
Ensure that the directory is available & accessible in the working directory.
In this case, a function like below needs to be called at the start of the application.
function initialize() {
const exists = fs.existsSync('./niktoResults');
if(exists === true) {
return;
}
fs.mkdirSync('./niktoResults')
}
Error caused by directory not existing, create a directory if it does not exist.
function create(text, directory, filename)
{
if (!fs.existsSync(directory)) {
fs.mkdirSync(directory);
console.log('Directory created');
create(text, directory);
} else {
fs.writeFile(`${directory}/${filename}`, `${text}`, function (error) {
if (error) {
throw error;
} else {
console.log('File created');
}
});
}
}
create('Text', 'directory', 'filename.txt');
I have tried several methods to delete my photo, especially using fs.unlink but it seems not working at all, you can see from picture below that i save my photos in assets->img->products
and so my database looks like this
and my code looks like this
router.get("/admin/products/:id/delete", (req, res) => {
Product.findByIdAndRemove(req.params.id, (err, photo) => {
if (err) {
req.flash("error", "deleting photo failed");
return res.render("/admin/products/");
}
fs.unlink(photo.image1, function() {
console.log(photo.image1);
return res.redirect("/admin/products");
});
});
});
what is wrong from my code that did not delete my photo from my file?
It can not delete photos because you are passing the relative path as the first parameter.
photo.image1 = assets/img/products/image1.jpg
Try passing the passing the absolute path( from the root directory of your machine).
fs.unlink("absolute-path-to-assetsParentFolder" + photo.image1, function() {
console.log(photo.image1);
return res.redirect("/admin/products");
});
I want to save files that I am getting from another server on my server but the problem is when I am calling createWriteStream it giving me the error :
no such file or directory, open
E:\pathtoproject\myproject\public\profile_14454.jpg
Here is my code which is in E:\pathtoproject\myproject\modules\dowload.js :
request.head(infos.profile_pic, function(err, res, body) {
const completeFileName = '../public/profile_14454.' + res.headers['content-type'].split('/')[1];
var imageStream = fs.createWriteStream(completeFileName);
imageStream.on('open', function(fd) {
console.log("File open");
request(infos.profile_pic).pipe(imageStream).on('close', function(body) {
consoleLog('Profile pic saved');
console.log('This is the content of body');
console.log(body);
connection.query('UPDATE user set photo=? where id=?', [completeFileName, lastID], function(err, result, fields) {
if (err) {
consoleLog('Error while update the profile pic');
}
});
})
});
});
When I removed the directory ../public/ and leave only the name of the file
profile_14454.' + res.headers['content-type'].split('/')[1] , it worked but the file was saved in the root directory of the project (E:\pathtoproject\myproject\).
What's wrong in what I am doing? How can I have the file saved under public directory?
I am using nodeJS 8.9.4
I tried with my small code .
var fs = require("fs");
var data = 'Simply Easy Learning';
// Create a writable stream
var writerStream = fs.createWriteStream('./airo/output.txt');
// Write the data to stream with encoding to be utf8
writerStream.write(data,'UTF8');
// Mark the end of file
writerStream.end();
// Handle stream events --> finish, and error
writerStream.on('finish', function() {
console.log("Write completed.");
});
writerStream.on('error', function(err){
console.log(err.stack);
});
console.log("Program Ended");
My code is in this path E:\syed ayesha\nodejs\nodejs now I want to store my file in airo folder which is in this path. So I used one dot for storing. Hope this helps.
I have a fairly simple script that attempts to read and then parse a JSON file. The JSON is very simple and I am pretty sure it is valid.
{
"foo": "bar"
}
Now, I have been trying to read it with fs.readFile. When read no errors occur and the returned data is a string. The only problem is that the string is empty.
I repeated my code but used fs.readFileSync, this returned the file perfectly using the same path. Both had a utf-8 encoding specified.
It is very simple code, as you can see.
fs.readFile('./some/path/file.json', 'utf8', function(err, data) {
if(!err) {
console.log(data); // Empty string...
}
});
console.log(fs.readFileSync('./some/path/file.json', 'utf8')); // Displays JSON file
Could it be permissions or ownership? I have tried a permission set of 755 and 777 to no avail.
I am running node v0.4.10. Any suggestions to point me in the right direction will be much appreciated. Thanks.
Edit: Here is a block of my actual code. Hopefully this will give you a better idea.
// Make sure the file is okay
fs.stat(file, function(err, stats) {
if(!err && stats.isFile()) {
// It is okay. Now load the file
fs.readFile(file, 'utf-8', function(readErr, data) {
if(!readErr && data) {
// File loaded!
// Now attempt to parse the config
try {
parsedConfig = JSON.parse(data);
self.mergeConfig(parsedConfig);
// The config was loaded and merged
// We can now call the callback
// Pass the error as null
callback.call(self, null);
// Share the news about the new config
self.emit('configLoaded', file, parsedConfig, data);
}
catch(e) {
callback.call(self, new Error(file + ': The config file is not valid JSON.'));
}
}
else {
callback.call(self, new Error(file + ': The config file could not be read.'));
}
});
}
else {
callback.call(self, new Error(file + ': The config file does not exist.'));
}
});
This is pretty weird.
The code looks.
var fs = require('fs');
fs.readFile('./jsonfile', 'utf8', function(err, data) {
if(err) {
console.error(err);
} else {
console.log(data);
parsedConfig = JSON.parse(data);
console.log(parsedConfig);
console.log(parsedConfig.foo);
}
});
Json file:
{
"foo": "bar"
}
output :
$ node test_node3.js
{
"foo": "bar"
}
{ foo: 'bar' }
bar
This is on node 0.4.10 , but i'm pretty sure it should work on all node version.
So why your data is empty ? You should check err in this case (like mine) and post the output if any. If you have no error, you may fill a bug on github