Download Module on NPM start - node.js

I want to know if there is a easy way to download file before other code runs. I need file.js to be downloaded first from my server because I am requiring it in my app on different places. I know I can do something like that.
let file = fs.createWriteStream(path.join(__dirname, 'file.js'));
let request = http.get("http://expample.com/file.js",
function(response) {
response.pipe(file);
});
But if I assume correctly, the file is written asynchronously. So when I require that file I have just empty object or error.
So what is the best way to download that file synchronously at first on npm start?

You can get such result using npm script pre hooks.
Assuming your start-up script is called "start" , in your package.json add
script called "prestart" in wich you want to run script that executes file downloading. and in will be automatically run when you call npm run start
For example:
package.json :
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"prestart": "node pre-start.js"
},
"author": "",
"license": "ISC"
}
index.js:
const value = require('./new-file.json');
console.log(value);
pre-start.js:
const fs = require('fs');
setTimeout(function() {
const value = {
"one" : 1,
"two" : 2
};
fs.writeFileSync('new-file.json', JSON.stringify(value));
}, 1000)
Here is a link to article with more detailed information:
http://www.marcusoft.net/2015/08/pre-and-post-hooks-for-npm-scripting.html
The other way is to run your other code after file is written:
let file = fs.createWriteStream(path.join(__dirname, 'file.js'));
let request = http.get("http://expample.com/file.js",
function(response) {
response.pipe(file);
file.on('finish',function(){
// run your code here
}
});

Related

my nodemon module is not working with node js

Basically, ive got start:"nodemon node.js" node.js is the actual file. but all it does is bring it up in my editor and port 3000 still isnt responding like it would if i typed node node.js every time i edited it. i did everything in the tutorial verbatim looked up the actual docs and searched stack and im still at a stand still, i am new to this and could use some help please,i installed it npm install nodemon --save-dev and would like to be able to do this in the local environment if possible, the modules are there, its just alot to past here, thanks in advance heres my code and such...
edit: when i run it i get
nod#1.0.0 start
nodemon node.js
in the terminal
const http = require('http');
const fs = require('fs');
const server = http.createServer((req,resp)=>{
const url = req.url;
const method = req.method;
{
"name": "nod",
"version": "1.0.0",
"description": "",
"main": "node.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon node.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"nodemon": "^2.0.15"
}
}
//.........................................................................................
if(url === '/'){
resp.write('<html>');
resp.write('<head><title>first</title></head>')
resp.write('<body>');
resp.write('<form action="/message"npmns npmno method="POST"><input type="text" name="message"><button type="submit">subn</button></form>');
resp.write('</body>');
resp.write('</html');
return resp.end();
}
if(url === '/message' && method=== 'POST'){
// resp.write('<html>');
// resp.write('<body');
const body =[];
req.on('data',(chunk)=>{
body.push(chunk);
})
req.on('end',(data)=> {
let message = body.toString().split('=')[1];
fs.writeFileSync('billy.txt', message);
})
resp.write('<form action="/" method="POST"><button type="submit">butt</button></form>');
// resp.write('</body>');
// resp.write('</html>');
return resp.end();
}
resp.setHeader('content-type','text/html');
resp.write('<html>');
resp.write('<head><title>firsttime</title></head>');
resp.write('<body><h1>hello again</h1></body>');
resp.write('</html>');
resp.end();
})
server.listen(3000);

Adding an NPM module to AWS Lambda Layer throws error: "SyntaxError: Cannot use import statement outside a module" when layer invoked from Lambda

Setting up an AWS Lambda Layer in NodeJS.
The steps are clear.
Setup the following directory structure:
-layer
utils.js
-nodejs
package.json
package-lock.json
-node_modules
The utils file has a simple piece of code in it, like this:
export function get_exchange_rate(curr1, curr2){
return 100.00;
}
The package.json file contains this:
{
"name": "layer",
"version": "1.0.0",
"description": "",
"type": "module",
"main": "utils.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "MIT",
"dependencies": {
}}
I zip up everything inside the layers folder and upload to Lambda Layers.
I attach the layer to the Lambda and my Lambda handler looks like this:
'use strict';
const opps = require('/opt/utils');
exports.handler = function(event, context) {
console.log("EXCHANGE RATE: ", opps.get_exchange_rate(1,2).toString())
};
I run it and it works fine.
But then I add an NPM module to the layer. I run npm install request, this adds request and dependencies to the node_modules folder and updates the packages.json file with the request dependency.
"dependencies": {
"request": "^2.88.2"
}
And in the utils.js file I add the following code:
import request from 'request'
export function get_status(){
request("http://www.google.com", (error, response, body) => {
console.log("error:", error);
console.log("statusCode:", response && response.statusCode);
console.log("body:", body);
});
}
I zip this all up and add to Lambda Layers, then call the get_status() function from Lambda, I receive this error:
SyntaxError: Cannot use import statement outside a module

Error on running a node application executable that executes a Powershell script

I have a node application that executes a Powershell script helloworld.ps1 . I want to make an executable of this node application. For this purpose I used Ziet/pkg
and I managed to create the executable for Linux, Mac and Windows but I am getting an error when I run the executable on any of the platforms.
Following is the code of node application:
let spawn = require('child_process').spawn, child;
let mqtt = require('mqtt');
let client = mqtt.connect('mqtt://13.58.186.254')
client.setMaxListeners(50);
runCheckScript = function () {
child = spawn("pwsh", ["./helloworld.ps1"]);
child.stdout.on("data", function (data) {
client.on('connect', () => {
})
console.log("Powershell Script: " + data);
});
child.stderr.on("data", function (data) {
console.log("Powershell Errors: " + data);
});
child.on("exit", function () {
client.publish("codeblock-poc", "Powershell Script finished");
console.log("Powershell Script finished");
client.end();
});
child.stdin.end();
}
module.exports = runCheckScript;
The above code is being run by the following file app.js:
runner = require('./powershell');
runCheckScript()
Following is the Powershell script code:
echo "Script working"
Get-Date
Write-Host "Press any key to continue ..."
When I run the node app simply by executing the node app.js command, I am able to get the desired output as shown in the following snapshot:
However, when I am running the executable on Windows I am getting the following error:
And On Mac I am getting the following error:
I have tried but kind of stuck now. Please guide me that how should I tackle this problem.
Following is the package.json file:
{
"name": "poweshell-executable",
"version": "1.0.0",
"description": "A simple poc to execute powershell thorugh node",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"pkg": {
"assets": "*.ps1"
},
"bin": "index.js",
"author": "Anshuman Upadhyay",
"license": "ISC",
"dependencies": {
"aws-iot-device-sdk": "^2.2.1",
"graphql": "^14.1.1",
"mqtt": "^2.18.8",
"node-powershell": "^3.3.1",
"time": "^0.12.0"
},
"resolutions": {
"nexe/fuse-box": "3.1.0"
}
}
I revisited the zeit/pkg docs and they have mentioned to add pkg tag in package.json(as shown above) and have the following code in index.js which is the value of bin property of the package.json.
path = require('path');
console.log(__dirname + '/' + 'helloworld.ps1');
path.join(__dirname + '/' + 'helloworld.ps1')
Now I am creating the executable as pkg package.json and now previous error has gone but the script is not executing:

Npm install with success but nodejs cannot find module 'db'

This error is so common but although I searched a lot of similar questions I did not found a solution to my problem. I installed the module with no problems using "npm install db".
The "server.js" is in the same folder as"node_moludes" and NPM created a "db" folder inside "node_moludes" with all the content.
All NPM commands return success (install, link, list etc), I even added the module to my "package.json" and it also installs with no problem just using "npm install -d".
Despite it all, when I run the server, Nodejs can't find the 'db' module... any help?
nodejs version: 0.10.26
npm version: 1.4.3
server.js
var http = require('http'),
url = require('url'),
db = require('db');
var send = function(response, data){
response.writeHead(200, {
'Content-Type': 'text/plain',
'Access-Control-Allow-Origin': '*'
});
response.end(JSON.stringify({data: data}));
};
http.createServer(function (request, response) {
var query = url.parse(request.url, true).query;
if(query.set) {
db.set(query.set, query.val || '');
send(response, true);
} else if (query.get) {
db.get(query.get, function(data){
send(response, data);
});
} else send(response, query);
}).listen(80);
package.json
{
"name": "xxxxx",
"version": "0.0.1",
"author": "rafaelcastrocouto",
"repository": "git://github.com/rafaelcastrocouto/xxxxx",
"dependencies": {
"db": ">= 1.00.x"
},
"engine": "node >= 0.10.x"
}
It appears the db module was setup without following some Node.js norms. It doesn't contain an index.* file or specify a "main" setting in its package.json to direct Node otherwise.
You should be able to reference the main file within the package directly:
var db = require('db/db');

cloud9 crypto is not working at all been trying for days

I am trying to get a setup work with utils, the problem is it can not find the crypto module.
I have install utils and crypto using npm install then when I run my script
node server.js casper.js
I get this error
Error: Cannot find module 'crypto'
phantomjs://bootstrap.js:289
phantomjs://bootstrap.js:254 in require
/var/lib/stickshift/53452520e0b8cd1d870002e1/app-root/data/828422/node_modules/utils/utils.js:7
/var/lib/stickshift/53452520e0b8cd1d870002e1/app-root/data/828422/node_modules/utils/utils.js:117
/var/lib/stickshift/53452520e0b8cd1d870002e1/app-root/data/828422/node_modules/utils/utils.js:118
TypeError: 'undefined' is not a function (evaluating 'utils.inherits(Nightmare, Casper)')
/var/lib/stickshift/53452520e0b8cd1d870002e1/app-root/data/828422/node_modules/nightmarejs/lib/nightmareClient.js:21
/var/lib/stickshift/53452520e0b8cd1d870002e1/app-root/data/828422/node_modules/nightmarejs/lib/nightmareTest.js:16
why can it not find crypto. I have tried all different ways to get this working, but no luck
does any one have any ideas?
package.json file
{
"name": "chat-example",
"version": "0.0.0",
"description": "A chat example to showcase how to use `socket.io` with a static `express` server",
"main": "server.js",
"repository": "",
"author": "Mostafa Eweda <mostafa#c9.io>",
"dependencies": {
"async": "~0.2.8",
"express": "~3.2.4",
"socket.io": "~0.9.14",
"phantomjs": "*",
"casperjs": "*",
"nightmarejs": "*",
"utils": "*",
"casper": "*"
}
}
server.js
var nightmareJS = require('./node_modules/nightmarejs/lib/nightmare').nightmare('test');
nightmareJS.notifyCasperMessage = function(msg) {
if(msg.type == 'statement') {
console.log(msg.msg);
console.log("Nightmare Server says hello.");
}
else if(msg.type == 'dateQuestion') {
console.log(msg.msg);
var d = new Date();
nightmareJS.sendCasperMessage({ time: d.toString(), timeNow: d.getTime()});
}
}
casper.js
casper.start('http://www.google.com', function() {
this.test.assertTitle('Google', 'Google has the correct title');
this.sendMessageToParent({ type: 'statement', msg: 'Hello Nightmare.'})
})
casper.then(function() {
this.waitForMessageResponse({ type: 'dateQuestion', msg: 'What time is it?'}, 'time', function() {
var d = new Date();
this.echo('Nightmare thinks the time is: ' + this.lastDataReceived.time);
this.log('Nightmare thinks the time is: ' + this.lastDataReceived.time, 'debug');
this.test.assert(Math.abs(this.lastDataReceived.timeNow - d.getTime()) < 1000, "Nightmare and Casper's times are within 1000 seconds of each other");
})
});
casper.run(function() {
this.test.done();
});
and then i run the files using
node server.js casper.js
i am trying to get nightmarejs to work but utils cannot find crypto
please someone help i so need this to work

Resources