How to use node-youtube-dl driver? - javascript

I use youtube-dl node driver to get information about videos on youtube, but I have trouble with ReferenceError - require is not defined (First line). I installed node-youtube-dl module on my laptop and the code is just taken from example in description. Is there anything else that I'm missing to do?
var youtubedl = require('youtube-dl');
var url = 'https://www.youtube.com/watch?v=9Q7Vr3yQYWQ';
ytdl.getInfo(url, function(err, info) {
if (err) throw err;
console.log('id:', info.id);
console.log('title:', info.title);
console.log('url:', info.url);
console.log('thumbnail:', info.thumbnail);
console.log('description:', info.description);
console.log('filename:', info._filename);
console.log('duration:', info.duration);
console.log('format_id:', info.format_id);
});

require() is a keyword in Node.js. It is used to import CommonJS modules like those in the npm registry. But it is not a keyword in your browser, where trying to use it will return a ReferenceError as you describe.
If you want to import npm modules using require() in your browser, you can try browserify or webpack. However, it is entirely possible (probable?) that youtube-dl is not compatible with browserify or webpack.
If you don't need to run it from a browser, you can put the code in a file (say, myFile.js) and run it from the command line with node:
node myFile.js

In your sample:
var youtubedl = require('youtube-dl');
However later you call it:
ytdl.getInfo(url, function(err, info)
just simply rename your require to ytdl, like this:
var ytdl = require('youtube-dl');

Related

How to output a consoles log to another file as regular text

I'm trying to print the result of my console.log to another .txt file, how would I make this happen? this is what my console.log looks like this: https://imgur.com/o2Vo471
I'm wanting this printed as regular text to an output file e.g 'output.txt'
I recommend to use Winston to achieve this.
You can set up Winston Transports to output in file winston.add(winston.transports.File, options)
Or if you don't wanna add any npm modules to your app you can just do this
var fs = require('fs');
module.exports = function(text) {
fs.appendFile('output.txt', text + '\n', function (err) {
if (err) throw err;
});
};
And save this to a file in your project directory, for example NameOfYourFile.js.
Then you can just require it in a file that you wanna make output from
var loger = require('./NameOfYourFile');
loger('Logs');
loger('Output');
loger('Working');
And just use loger instead of console.log. You also can easily rename it.
TypeScript version
First, install node modules
npm install #types/node --save-dev
Then create a file for your module, for example, NameOfYourFile.ts
import * as fs from 'fs';
export default function(text) {
fs.appendFile('output.txt', text + '\n', function (err) {
if (err) throw err;
});
};
Then you can import it like this
import loger from './NameOfYourFile';
loger('Logs');
loger('Output');
loger('Working');
Can you rewrite your program as a node app and then just run it from the Terminal window instead? Then, you wouldn't need to wrestle with this problem of getting your console output into a file... you could use node's fs instead (Node.js Write a line into a .txt file)
This answer works, but it isn't what i'm aiming for it will work for most other people i'd assume. you're gonna want to run your program like so:
npm start > output.txt
this will print your console output to the output.txt file I still need to achieve this with node fs so i'd appreciate anymore answers

Node JS Error when copying file across partition. How to resolve this issue? [duplicate]

I'm trying to move a file from one partition to another in a Node.js script. When I used fs.renameSync I received Error: EXDEV, Cross-device link. I'd copy it over and delete the original, but I don't see a command to copy files either. How can this be done?
You need to copy and unlink when moving files across different partitions. Try this,
var fs = require('fs');
//var util = require('util');
var is = fs.createReadStream('source_file');
var os = fs.createWriteStream('destination_file');
is.pipe(os);
is.on('end',function() {
fs.unlinkSync('source_file');
});
/* node.js 0.6 and earlier you can use util.pump:
util.pump(is, os, function() {
fs.unlinkSync('source_file');
});
*/
I know this is already answered, but I ran across a similar problem and ended up with something along the lines of:
require('child_process').spawn('cp', ['-r', source, destination])
What this does is call the command cp ("copy"). Since we're stepping outside of Node.js, this command needs to be supported by your system.
I know it's not the most elegant, but it did what I needed :)
One more solution to the problem.
There's a package called fs.extra written by "coolaj86" on npm.
You use it like so:
npm install fs.extra
fs = require ('fs.extra');
fs.move ('foo.txt', 'bar.txt', function (err) {
if (err) { throw err; }
console.log ("Moved 'foo.txt' to 'bar.txt'");
});
I've read the source code for this thing. It attempts to do a standard fs.rename() then, if it fails, it does a copy and deletes the original using the same util.pump() that #chandru uses.
to import the module and save it to your package.json file
npm install mv --save
then use it like so:
var mv = require('mv');
mv('source_file', 'destination_file', function (err) {
if (err) {
throw err;
}
console.log('file moved successfully');
});
I made a Node.js module that just handles it for you. You don't have to think about whether it's going to be moved within the same partition or not. It's the fastest solution available, as it uses the recent fs.copyFile() Node.js API to copy the file when moving to a different partition/disk.
Just install move-file:
$ npm install move-file
Then use it like this:
const moveFile = require('move-file');
(async () => {
await moveFile(fromPath, toPath);
console.log('File moved');
})();

Traversing directory in Node (Grunt)

Having a strange issue when building a grunt plugin.
Basically, I'd like to use a node_module in my grunt task itself. To do this, I want to traverse a level up, then down into the node modules to call their one file specifically.
Originally, I wanted to do this:
../node_modules/github-changes/bin/index.js
However, I get the following error:
Warning: Command failed: /bin/sh: 1: ../node_modules/github-changes/bin/index.js: not found
Use --force to continue.
So, for now I have a hack on using Node's __dirname variable, but it's not very pretty:
var dirHack = __dirname.replace("/tasks", ""), // Terrible hack, need to fix
ghC = dirHack + '/node_modules/github-changes/bin/index.js';
This works, but I'd love to avoid it.
You can see the line here.
What's missing that's causing that error? Am I missing something here?
If github-changes is a dependency, you can resolve a path to file within the package using ghC = require.resolve('github-changes/bin/index.js').
But you're getting that error because you're trying to run that file as a shell script, which it is not. You need to run it with node. The easiest way to find the path to the node executable is process.execPath. See http://nodejs.org/api/process.html#process_process_execpath
Here is an example:
var exec = require('child_process').exec;
var ghC = require.resolve('github-changes/bin/index.js');
exec(process.execPath + ' ' + ghC, function(error) {});

How do I load my script into the node.js REPL?

I have a script foo.js that contains some functions I want to play with in the REPL.
Is there a way to have node execute my script and then jump into a REPL with all the declared globals, like I can with python -i foo.py or ghci foo.hs?
There is still nothing built-in to provide the exact functionality you describe. However, an alternative to using require it to use the .load command within the REPL, like such:
.load foo.js
It loads the file in line by line just as if you had typed it in the REPL. Unlike require this pollutes the REPL history with the commands you loaded. However, it has the advantage of being repeatable because it is not cached like require.
Which is better for you will depend on your use case.
Edit: It has limited applicability because it does not work in strict mode, but three years later I have learned that if your script does not have 'use strict', you can use eval to load your script without polluting the REPL history:
var fs = require('fs');
eval(fs.readFileSync('foo.js').toString())
i always use this command
node -i -e "$(< yourScript.js)"
works exactly as in Python without any packages.
I made Vorpal.js, which handles this problem by turning your node add into an interactive CLI. It supports a REPL extension, which drops you into a REPL within the context of your running app.
var vorpal = require('vorpal')();
var repl = require('vorpal-repl');
vorpal
.delimiter('myapp>')
.use(repl)
.show()
.parse(process.argv);
Then you can run the app and it will drop into a REPL.
$ node myapp.js repl
myapp> repl:
Another way is to define those functions as global.
global.helloWorld = function() { console.log("Hello World"); }
Then preload the file in the REPL as:
node -r ./file.js
Then the function helloWorld can be accessed directly in the REPL.
Here's a bash function version of
George's answer:
noderepl() {
FILE_CONTENTS="$(< $1 )"
node -i -e "$FILE_CONTENTS"
}
If you put this in your ~/.bash_profile you can use it like an alias, i.e.:
noderepl foo.js
I created replpad since I got tired of reloading the script repeatedly.
Simply install it via: npm install -g replpad
Then use it by running: replpad
If you want it to watch all files in the current and all subdirectories and pipe them into the repl when they change do: replpad .
Check out the videos on the site to get a better idea of how it works and learn about some other nice features that it has like these:
access core module docs in the repl via the dox() function that is added to every core function, i.e. fs.readdir.dox()
access user module readmes in the repl via the dox() function that is added to every module installed via npm,
i.e. marked.dox()
access function's highlighted source code, info on where function was defined (file, linenumber) and function
comments and/or jsdocs where possible via the src property that is added to every function, i.e. express.logger.src
scriptie-talkie support (see .talk command)
adds commands and keyboard shortcuts
vim key bindings
key map support
parens matching via match token plugin
appends code entered in repl back to file via keyboard shortcut or .append command
See: https://github.com/thlorenz/replpad
Why not load the file into an interactive node repl?
node -h
-e, --eval script evaluate script
-i, --interactive always enter the REPL even if stdin
node -e 'var client = require("./build/main/index.js"); console.log("Use `client` in repl")' -i
Then you can add to package.json scripts
"repl": "node -e 'var client = require(\"./build/main/index.js\"); console.log(\"Use `client` in repl\")' -i",
tested using node v8.1.2
Currently you can't do that directly, but you can mylib = require('./foo.js') in the REPL. Remember methods are exported, not declared as globals.
replpad is cool, but for a quick and easy way to load a file into node, import its variables and start a repl, you can add the following code to the end of your .js file
if (require.main === module){
(function() {
var _context = require('repl').start({prompt: '$> '}).context;
var scope = require('lexical-scope')(require('fs').readFileSync(__filename));
for (var name in scope.locals[''] )
_context[scope.locals[''][name]] = eval(scope.locals[''][name]);
for (name in scope.globals.exported)
_context[scope.globals.exported[name]] = eval(scope.globals.exported[name]);
})();
}
Now if your file is src.js, running node src.js will start node, load the file, start a REPL, and copy all the objects declared as var at the top level as well as any exported globals.
The if (require.main === module) ensures that this code will not be executed if src.js is included through a require statement. I fact, you can add any code you want to be excuted when you are running src.js standalone for debugging purposes inside the if statement.
Another suggestion that I do not see here: try this little bit of code
#!/usr/bin/env node
'use strict';
const repl = require('repl');
const cli = repl.start({ replMode: repl.REPL_MODE_STRICT });
cli.context.foo = require('./foo'); // injects it into the repl
Then you can simply run this script and it will include foo as a variable
Old answer
type test.js|node -i
Will open the node REPL and type in all lines from test.js into REPL, but for some reason node will quit after file ends
Another problem is, that functions will not be hoisted.
Better answer
node -e require('repl').start({useGlobal:true}); -r ./test2.js
Then all globals declared without var within test2.js will be available in the REPL
not sure why var a in global scope will not be available
There is an Official Node.js REPL that supports also async methods
console.js
const repl = require('repl')
const mongoose = require('mongoose')
const run = async () => {
await mongoose.connect(process.env.DB_URL, {
useNewUrlParser: true,
useUnifiedTopology: true
})
const r = repl.start(`(${process.env.NODE_EN}) ⚡️ `)
r.context.User = require('./src/models/user.model')
r.context.mongoose = mongoose
console.log(`Ready 🚀`);
}
run()
Start the console:
NODE_OPTIONS=--experimental-repl-await node console.js
User model its exposed to console
await User.find({})
source

How do I move file a to a different partition or device in Node.js?

I'm trying to move a file from one partition to another in a Node.js script. When I used fs.renameSync I received Error: EXDEV, Cross-device link. I'd copy it over and delete the original, but I don't see a command to copy files either. How can this be done?
You need to copy and unlink when moving files across different partitions. Try this,
var fs = require('fs');
//var util = require('util');
var is = fs.createReadStream('source_file');
var os = fs.createWriteStream('destination_file');
is.pipe(os);
is.on('end',function() {
fs.unlinkSync('source_file');
});
/* node.js 0.6 and earlier you can use util.pump:
util.pump(is, os, function() {
fs.unlinkSync('source_file');
});
*/
I know this is already answered, but I ran across a similar problem and ended up with something along the lines of:
require('child_process').spawn('cp', ['-r', source, destination])
What this does is call the command cp ("copy"). Since we're stepping outside of Node.js, this command needs to be supported by your system.
I know it's not the most elegant, but it did what I needed :)
One more solution to the problem.
There's a package called fs.extra written by "coolaj86" on npm.
You use it like so:
npm install fs.extra
fs = require ('fs.extra');
fs.move ('foo.txt', 'bar.txt', function (err) {
if (err) { throw err; }
console.log ("Moved 'foo.txt' to 'bar.txt'");
});
I've read the source code for this thing. It attempts to do a standard fs.rename() then, if it fails, it does a copy and deletes the original using the same util.pump() that #chandru uses.
to import the module and save it to your package.json file
npm install mv --save
then use it like so:
var mv = require('mv');
mv('source_file', 'destination_file', function (err) {
if (err) {
throw err;
}
console.log('file moved successfully');
});
I made a Node.js module that just handles it for you. You don't have to think about whether it's going to be moved within the same partition or not. It's the fastest solution available, as it uses the recent fs.copyFile() Node.js API to copy the file when moving to a different partition/disk.
Just install move-file:
$ npm install move-file
Then use it like this:
const moveFile = require('move-file');
(async () => {
await moveFile(fromPath, toPath);
console.log('File moved');
})();

Categories

Resources