Webshot doesn't save any image - javascript

I try to use node package Webshot, it executes the function, print "OK" to console, but never save any file to the folder. What am I missing here?
if (Meteor.isServer) {
var webshot = Meteor.npmRequire('webshot');
Meteor.methods({
'snapshot':function () {
webshot('google.com', './google.png', function (err) {
if (err) return console.log(err);
console.log('OK');
});
}
})
}

I just installed webshot and tried it.
You will find the .png in .meteor/local/build/programs/server or thereabouts

Related

how to move a file/image if not used by another app or process NodeJS

I'm trying to make a function that checks if file is opened or in use by another app or process using fs
and here is my attempt to do this
function isFileInUse() {
try {
const file = path.join(__dirname, '20200201072955946-2.jpg');
//try to open file for checking if it is in use
fs.access(file, fs.constants.W_OK, (err) => {
if (err) {
console.log('File is in use');
} else {
console.log('File is not in use');
}
});
return false;
}
catch(error) {
console.log(error);
return true;
}
}
isFileInUse()
this code somehow move the the image with no error even if it's run by another app like notepad++ or by image viewer
if someone can tell me what i'm doing wrong on this matter or help with this . that be great
thanks in advance

Is there a better way to call a .env file exists check function in cypress?

I would like to check if there is a .env file exists in the root folder before running the test. I have added below function in the index.js but it is not checking if the file exists. Could someone please advise the issue here ?
cypress/ plugins/ index.js
const filePath = "../../../.env";
module.exports = (on, config) => {
on('file:preprocessor', cucumber()),
on('before:browser:launch', (browser, launchOptions) => {
console.log("Print browser name: "+browser.name);
fileCheck(filePath); // calling the function here
});
};
function fileCheck(filePath) => {
try {
if (fs.existsSync(filePath)) {
console.log("Awesome ! .env file exists in the root directory ! ");
}
} catch(err) {
console.error(err)
console.log("Oh !, .env file is missing, please add !");
}
}
Maybe it's enough to check it in a before action, then you can do:
before(() => {
cy.on('fail', (error) => {
error.message = 'Oh !, .env file is missing, please add !';
throw error;
})
cy.readFile('.env', {timeout: 50}).should('exist');
});

I would like guidance to create some directories

What I need:
Create a folder on the desktop, within that folder create another called "img" and inside img create "home".
The way I managed to do it, But I know it's not the ideal way ... I'm still learning, thank you for your patience!
Any suggestions to improve this?
var nome = 'teste';
const dir = `C:/Users/mathe/Desktop/${nome}`;
if (!fs.existsSync(dir)){
fs.mkdir(dir, (err) => {
if(err){
console.log(err)
}else{
dirImg = dir+'/'+'img';
fs.mkdirSync(dirImg)
fs.mkdirSync(dirImg+'/'+'home')
console.log('Sucess')
}
});
}else{
console.log(`File $ {name} cannot be created because it already exists!`)
}
mkdir has a recursive option, so:
if (!fs.existsSync(dir)){
fs.mkdir(`${dir}/img/home`, {recursive: true}, (err) => {
// ^^^^^^^^^^^^^^^^^−−^^^^^^^^^^^^^^^^^^−−−−−−−−−−−−−−−−−−−
if(err){
console.log(err)
}else{
console.log('Sucess')
}
});
}else{
console.log(`File $ {name} cannot be created because it already exists!`)
}
Side note: It's generally not a good idea to check for existence before creating. Instead, just go ahead and try to create it. From the documentation:
Calling fs.mkdir() when path is a directory that exists results in an error only when recursive is false.
So:
fs.mkdir(`${dir}/img/home`, {recursive: true}, (err) => {
// ^^^^^^^^^^^^^^^^^−−^^^^^^^^^^^^^^^^^^−−−−−−−−−−−−−−−−−−−
if(err){
console.log(err)
}else{
console.log('Sucess')
}
});

Error: ENOENT: no such file or directory, uv_chdir at process.chdir when creating a directory and changing into it

I'm trying to write a small app that installs some files and modules in a new folder, but I keep getting this error:
{ Error: ENOENT: no such file or directory, uv_chdir
at process.chdir (/home/aboardwithabag/LaunchProject/node_modules/graceful-fs/polyfills.js:20:9)
at cd (/home/aboardwithabag/LaunchProject/index.js:26:13)
Below is my code. Can someone help me out?
// node LaunchProject projectName
// Installs a server, node modules, and index page.
// not working due to issues with chdir.
const cp = require('child_process');
const fse = require('fs-extra');
// const path = require('path');
const project = process.argv[2];
let server ="";
let home = "";
function make (cb){
fse.mkdirs(project, function(err){
if (err){
console.error(err);
}
});
cb;
}
function cd(cb){
try{
process.chdir('/'+project);
cb;
} catch (err) {
console.error(err);
return;
}}
function install(cb){
cp.exec('npm install express', function(err){
if (err){
console.error(err);
} else {
console.log('Express Installed.');
cp.exec('npm install ejs', function(err){
if (err){
console.error(err);
} else{
console.log('Ejs Installed.');
fse.outputFile('index.js', server);
fse.outputFile('public/index.html', home);
}});
}
});
cb;
}
make(cd(install(console.log(project + ' created.'))));
unless the folder name you assign to the project variable (in this case it seems to be "uv_chdir") is located at the root folder of your HDD, below line will give the error:
process.chdir('/'+project);
make sure you give correct path to the program arguments. (in this case argv[2])
Or you may remove the leading '/' and make the path relative.
It seems there are some issues with this code.
cb callbacks provided as function arguments need to be called not after the async calls, but inside the callbacks of these calls. For example:
function make (cb){
fse.mkdirs(project, function(err){
if (err){
console.error(err);
}
cb();
});
}
The last call chain make(cd(install(console.log(project + ' created.')))); would work only with sync calls in reversed order and only if they returned needed callbacks.
That is why your new dir is not ready when you try to use it: your async functions do not actually wait for each other.
You do not call your callbacks as cb(), just mention them as cb. You should call them.
With minimal changess, your code can be refactored in this way:
'use strict';
const cp = require('child_process');
const fse = require('fs-extra');
const project = process.argv[2];
let server = '';
let home = '';
make(cd, install, () => { console.log(project + ' created.'); });
function make(cb1, cb2, cb3) {
fse.mkdirs(project, (err) => {
if (err) {
console.error(err);
}
cb1(cb2, cb3);
});
}
function cd(cb1, cb2) {
try {
process.chdir('/' + project);
cb1(cb2);
} catch (err) {
console.error(err);
}
}
function install(cb1) {
cp.exec('npm install express', (err) => {
if (err) {
console.error(err);
} else {
console.log('Express Installed.');
cp.exec('npm install ejs', (err) => {
if (err) {
console.error(err);
} else {
console.log('Ejs Installed.');
fse.outputFile('index.js', server);
fse.outputFile('public/index.html', home);
cb1();
}
});
}
});
}
But it is rather brittle and unnecessarily complicated in this form. Maybe it would be simpler to inline your functions each in other.
when I use PM2,i got this error "no such file or directory, uv_chdir"
the resolvent is :
first,I use 'pm2 delete' to delete old process
second,I use 'pm2 start',then ok
ps : just change your code or use 'pm2 reload' or 'pm2 restart' would not be ok.
more detail , you can see "https://blog.csdn.net/u013934914/article/details/51145134"

Let NodeJS application update itself using NPM

Hej There,
I'm trying to add some non-conventional functionality to my NodeJS application but I'm having some trouble.
What I'm trying to do is the following:
I want to update my server code from the client. (An auto-update functionality if you will.)
My first attempt was to utilize the NPM API and run:
npm.commands.install([package], function(err, data)
But of course this results in an error telling me NPM can not install while the server is running.
My second attempt was spawning NPM update using the following code:
spawnProcess('npm', ['update'], { cwd: projectPath }, done);
The spawnProcess function is a generic spawn function:
var projectPath = path.resolve(process.cwd());
var spawnProcess = function(command, args, options, callback) {
var spawn = require('child_process').spawn;
var process = spawn(command, args, options);
var err = false;
process.stdout.on('data', function(data) {
console.log('stdout', data.toString());
});
process.stderr.on('data', function(data) {
err = true;
console.log('stderr', data.toString());
});
if (typeof callback === 'function') {
process.on('exit', function() {
if (!err) {
return callback();
}
});
}
};
But this gives me a stderr followed by a 'CreateProcessW: can not find file' error.
I don't quite know what I'm doing wrong.
If all else fails I thought it might be possible to write a shellscript killing Node, updating the application and then rebooting it. Something like:
kill -9 45728
npm update
node server
But I don't know if this is a plausible solution and how I would go about executing it from my node server.
I'd rather have the spawn function working of course.
Any help is welcome.
Thanks in advance!
So I finally fixed this issue. If someone is interested how I did it, this is how:
I built a function using the NPM api to check if the current version is up to date:
exports.checkVersion = function(req, res) {
npm.load([], function (err, npm) {
npm.commands.search(["mediacenterjs"], function(err, data){
if (err){
console.log('NPM search error ' + err);
return;
} else{
var currentInfo = checkCurrentVersion();
for (var key in data) {
var obj = data[key];
if(obj.name === 'mediacenterjs' && obj.version > currentInfo.version){
var message = 'New version '+obj.version+' Available';
res.json(message);
}
}
}
});
});
}
var checkCurrentVersion = function(){
var info = {};
var data = fs.readFileSync('./package.json' , 'utf8');
try{
info = JSON.parse(data);
}catch(e){
console.log('JSON Parse Error', e);
}
return info;
};
If the version is not up to date I initiate a download (in my case the github master repo url) using node-wget:
var wget = require('wget');
var download = wget.download(src, output, options);
download.on('error', function(err) {
console.log('Error', err);
callback(output);
});
download.on('end', function(output) {
console.log(output);
callback(output);
});
download.on('progress', function(progress) {
console.log(progress * 100);
});
The callback kicks off the unzip function bases on #John Munsch 'Self help' script but I added a check to see if there was a previous unzip attempt and if so, I delete the folder:
if(fs.existsSync(dir) === false){
fs.mkdirSync(dir);
} else {
rimraf(dir, function (err) {
if(err) {
console.log('Error removing temp folder', err);
} else {
fileHandler.downloadFile(src, output, options, function(output){
console.log('Done', output);
unzip(req, res, output, dir);
});
}
});
}
console.log("Unzipping New Version...");
var AdmZip = require("adm-zip");
var zip = new AdmZip(output);
zip.extractAllTo(dir, true);
fs.openSync('./configuration/update.js', 'w');
The openSync function kicks off my 'NodeMon' based file (https://github.com/jansmolders86/mediacenterjs/blob/master/server.js) which kills the server because it is listing for changes to that specific file. Finally it restart and starts the following functions:
function installUpdate(output, dir){
console.log('Installing update...');
var fsExtra = require("fs.extra");
fsExtra.copy(dir+'/mediacenterjs-master', './', function (err) {
if (err) {
console.error('Error', err);
} else {
console.log("success!");
cleanUp(output, dir);
}
});
}
function cleanUp(output, dir) {
console.log('Cleanup...');
var rimraf = require('rimraf');
rimraf(dir, function (e) {
if(e) {
console.log('Error removing module', e .red);
}
});
if(fs.existsSync(output) === true){
fs.unlinkSync(output);
console.log('Done, restarting server...')
server.start();
}
}
Thanks to everyone that helped me out!
Untested!
Have you tried the "prestart" npm script handle? Of course this would mean that you'd use npm to run your server: npm start
In your package.json (if you have) :
{ "scripts" :
{
"start" : "node server.js",
"prestart" : "scripts/customScript.js"
}
}
NPM start command is implicitly defaulted to "start": "node server.js". If your server script is called server.js, there is no need to include this. You can do your npm install on the customScript.js or might be able to call npm install directly though I haven't tested this.
You can also assign/read your handler using the environment variable process.env.npm_package_scripts_prestart
It doesn't use NPM to accomplish it but here's a working experiment I put together a while back because I wanted to be able to build a self-updating app using Node.js for installation on people's machines (think apps like SABnzbd+, Couch Potato, or the Plex Media Server).
The Github for the example code is here: https://github.com/JohnMunsch/selfhelp
I got the example to the point where it would automatically notify you when a new version was available and then download, update, and restart itself. Even if you don't end up using it as-is, you should be able to get some ideas from it.

Categories

Resources