$ node --version
20.10.0
$ node
> console.log('hello world')
// whereAmI.js
console.log('You are here:');
const currentDir = process.cwd();
setTimeout(() => console.log(currentDir), 1000);
$ node whereAmI.js
Browser | Node | |
---|---|---|
setTimeout | y | y |
process | n | y |
window | y | n |
$ mkdir where-am-i
$ mv whereAmI.js where-am-i/
$ cd where-am-i
$ npm init
package.json
{
"name": "where-am-i",
"version": "1.0.0",
"description": "Find out where your JS script is running",
"main": "whereAmI.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Anjana",
"license": "ISC"
}
$ npm run test
Error: no test specified
"scripts": [
"find-me": "node whereAmI.js"
]
$ npm run find-me
$ npm install cowsay
or
$ npm i cowsay
import { say } from 'cowsay'
const currentDir = process.cwd();
const message = 'Moo are here:\n' + currentDir
console.log(say({ text: message}));
(and other problems)
Original Node module system, still around
const cowsay = require('cowsay');
module.exports = {
mooove: () => cowsay.say({text: 'Get going'})
};
The new(ish) hotness, supported by browsers too
import { say } from 'cowsay';
export const mooove = () => cowsay.say({text: 'Get going'})
<script type="module">
// import away
</script>
Option 1: .mjs
extension
Option 2: "type": "module"
in package.json
% npm run find-me
> where-am-i@1.0.0 find-me
> node whereAmI.js
_____________________________________
/ Moo are here: \
\ /Users/anjana/Dev/vakila/where-am-i /
-------------------------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
Not to worry, the community has come up with helpful tools & frameworks!
$ npm create vite@latest
Uses create-vite
npm package to bootstrap a project from a template
getUserMedia
const avStream = await navigator.mediaDevices.getUserMedia({
audio: true,
video: true
});
const video = document.querySelector('video');
video.srcObject = avStream;
await video.play();
const canvas = document.querySelector('canvas');
const context = canvas.getContext("2d");
context.fillStyle = "yellow";
context.fillRect(0, 0, 100, 100); // (x, y, width, height)
context.fillStyle = "black";
context.font = "50px sans-serif";
context.fillText("JS", 40, 90, 50); // (text, x, y, maxWidth)
context.drawImage(video, 0, 0); // (x, y)