I am new to node.js so I am trying to understand promises and wait on node.js. I want to print the file note.txt.
Here is my code
var fs = require('fs');
fs.readFile('note.txt','utf8').then(contents => console.log(contents))
.catch(err => console.error(err));
When I run above code. I get the following error.
fs.readFile('note.txt','utf8').then(contents => console.log(contents))
TypeError: Cannot read property 'then' of undefined
at Object.<anonymous> (/Applications/nodeApps/test/index.js:13:31)
at Module._compile (module.js:635:30)
at Object.Module._extensions..js (module.js:646:10)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Function.Module.runMain (module.js:676:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
And I try another method for the same thing.
var fs = require('fs');
async function read_file(){
var file_data = await fs.readFile('note.txt','utf8');
return file_data;
}
console.log(read_file());
And I get following error
Promise { <pending> }
(node:6532) [DEP0013] DeprecationWarning: Calling an asynchronous function without callback is deprecated.
I get the same error when I run with --harmony. I m not sure if there is bug on my code or what is wrong. Please help me understand.
My Environment
Node version: v8.9.0
node -p process.versions.v8: 6.1.534.46
You're getting errors because fs.readfile doesn't return a promise; hence then doesn't exist. For you to use the function as a promise, you will need to wrap it up as a promise; you could use something like bluebird or Q.
Thank you for the answers. I learned that function must return promise in order to use then() and catch(). So the code should be like this
var fs = require('fs');
function read_file(){
return new Promise(function(resolve, reject) {
fs.readFile('note.txt','utf8',function(err,file){
if(err){
return reject(err);
}else{
resolve(file);
}
});
});
}
read_file().then(
(data)=>{
console.log('success: '+data);
}
).catch((err)=>{
console.log('error: ',err);
});
If you use NodeJs v10, try fs.promises:
var fs = require('fs').promises; // v10.0 use require('fs/promises')
fs.readFile('note.txt','utf8').then(contents => console.log(contents))
.catch(err => console.error(err));
If not, use readFileSync:
// This code can use for node v10 or lowwer
var fs = require('fs');
var data = fs.readFileSync('a.json');
console.log(data);
try to use the async await
function (async err => {
if (err) {
console.err ....}
await .... <other function included or comes after then .>
await ... <other function included>
})
Related
I have a simple dc bot, code goes like this. I tried to simplfy it to make it more readable
const client = new Discord.Client();
...
client.on('ready', () => {
client.channels.cache.get('315445287374028800').send("works here");
});
setInterval(( () =>{
try{
removeHTML(downloadHTML);
} catch(err){
console.log(err);
}
}),30000);
...
...
let removeHTML = function(callback){
client.channels.cache.get('315445287374028800').send("WORKS HERE");
readHTML();
...
}
let readHTML = function(){
console.log("dolar is read");
//client.channels.cache.get('315445287374028800').send("DOESNT WORK HERE");
fs.readFile(dir + '/index.html' , 'utf-8', function(err,html){
if(err)
console.log(err);
else{
//client.channels.cache.get('315445287374028800').send("DOESNT WORK HERE");
if(isPeak){
//client.channels.cache.get('315445287374028800').send("DOESNT WORK HERE");
}
}
});
}
seems like send function doesnt work in callback functions but how can i fix this?
Error type: same error for all ("DOESNT WORK HERE") lines :
TypeError: Cannot read property 'send' of undefined
at readHTML (C:\Users\user\Desktop\Discord Bot\index.js:142:18)
at Object.<anonymous> (C:\Users\user\Desktop\Discord Bot\index.js:182:1)
at Module._compile (internal/modules/cjs/loader.js:1015:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)
at Module.load (internal/modules/cjs/loader.js:879:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Function.executeUserEntryPoint [as runMain]
I have turned all functions to async-await instead and it worked
Hi everyone I'm beginner in Nodejs and mongoose.I have tried to insert and retrieve the data in mongoose.I'm using async await function to execute one by one (sequence).can anyone help me? Thanks in advance....
i.e: I want to execute (Async await)concept (SEQUENCE STEP)
1.connect the db
2.create the user
3.find the user.
I'm getting the error :
async function calltaskone(){
^^^^^^^^
SyntaxError: Unexpected token function
at Object.exports.runInThisContext (vm.js:78:16)
at Module._compile (module.js:543:28)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:420:7)
at startup (bootstrap_node.js:139:9)
at bootstrap_node.js:535:3
Code for your reference:
'use strict';
const mongoose=require('mongoose');
const calldbconnect=()=>{
return new Promise((resolve,reject)=>{
if(true){
mongoose.connect('mongodb://vdsd:vdwdwh12dw3,#ds11dwdw.mlab.com:1w5664/vorganisation',{useNewUrlParser:true},(err,db)=>{
if(err){
console.log(err);
reject('Db is not connected');
}
else{
resolve('Db is connected');
}
});
}
});
}
const schemadesign=new mongoose.Schema({
clientName:String,
clientId:Number,
clientAddress:String
});
const modeldata=mongoose.model('clientInfo',schemadesign);
const data=[{
clientName:'VIGNESH Mack',
clientId:4128,
clientAddress:'UK'
},{
clientName:'VIGNESH Tokyo',
clientId:4988,
clientAddress:'USA'
}];
function calldatasave(){
return new Promise((resolve,reject)=>{
modeldata.create(data,(err,a,b)=>{
if(err){
reject(`Error occured while data saved ${err}`);
}
else{
resolve('Data saved successfully');
}
});
});
}
const calldatafind=()=>{
return new Promise((resolve,reject)=>{
if(true){
console.log('try to find');
modeldata.find({'clientId':4988},(err,data)=>{
if(err){
reject(`Error occured while find data: ${err}`)
}
else{
console.log(data);
resolve('Data found');
}
});
}
});
}
async function calltaskone(){
const a=await calldbconnect();
console.log(a);
const b=await calldatasave();
console.log(b);
const c=await calldatafind();
console.log(c);
}
calltaskone();
I believe you're using a older version of Node. Async functions are not supported by Node versions older than version 7.6. You can check here.
If you want to use async/await then you need to transpile using Babel for your node version.
Edit:
As you said you are using v7.3, you can use (from v7.0 to v7.5) the --harmony flag to enable the experimental features. To know more about the flag, check this out: What does `node --harmony` do?
Actually I have tried one code. This code is working fine but I want to access this information outside of callback function. But i am unable to find solution.
var prompt = require('prompt');
prompt.start();
prompt.get(['username', 'email'], function (err, result) {
console.log('Command-line input received:');
console.log(' username: ' + result.username);
console.log(' email: ' + result.email);
data = result.username;
});
console.log(data);
Here if i'm trying to retrieve print data variable it show's error.
Admins-MacBook-Pro:Basic node programs Sandeep$ node Node3.js
prompt: username: /Users/Sandeep/Desktop/NodeJS/Node example/Basic node programs/Node3.js:22
console.log(data);
^
ReferenceError: data is not defined
at Object.<anonymous> (/Users/Sandeep/Desktop/NodeJS/Node example/Basic node programs/Node3.js:22:13)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3
You could use promise, check docs about promise and newer es 6 Async/ await. With promise you could use something like this:
var prompt = require('prompt');
function getPromt () { return new Promise( (resolve, recect) => {
prompt.start();
prompt.get(['username', 'email'], function (err, result) {
console.log('Command-line input received:');
console.log(' username: ' + result.username);
console.log(' email: ' + result.email);
resolve( result.username);
});
});
}
getPromt().then(data =>
console.log('After promise ' + data), ()=>{});
"You won't be able to access that variable outside the callback function. The reason is, the Node.js has a special feature of passing a callback function as the next block of code to be executed after performing an asynchronous IO task."
Refer to this one: how can find return variable value outside anonymous function in node js mysql query function
You can also check this link to learn how to handle with async flow: http://book.mixu.net/node/ch7.html
I am trying to use async/await in NodeJS but my script is throwing a syntax error.
I was under the impression that async/await is supported naively since Node 7.6. When I run node -v I get v7.10.0.
Here is the contents of index.js:
async function getValueAsync() {
return new Promise(function(resolve) {
resolve('foo');
});
}
let value = await getValueAsync();
console.log(value);
But when I invoke this script with node index.js I get:
let value = await getValueAsync();
^^^^^^^^^^^^^
SyntaxError: Unexpected identifier
at createScript (vm.js:53:10)
at Object.runInThisContext (vm.js:95:10)
at Module._compile (module.js:543:28)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:427:7)
at startup (bootstrap_node.js:151:9)
I am running Linux Mint 18.1.
How can I get my script to compile and run?
await is only valid inside async functions, so you need, for example, an async IIFE to wrap your code with:
void async function() {
let value = await getValueAsync();
console.log(value);
}();
And, since return values from async functions are wrapped by a promise, you can shorten getValueAsync to simply this:
async function getValueAsync() {
return 'foo';
}
Or don't mark it as async and return a promise from it:
function getValueAsync() {
return new Promise(function(resolve) {
resolve('foo');
});
}
I've installed nodejs 7.3.0 and I have this code:
let getContent = function (url) {
// return new pending promise
return new Promise((resolve, reject) => {
// select http or https module, depending on reqested url
const lib = url.startsWith('https') ? require('https') : require('http');
const request = lib.get(url, (response) => {
// handle http errors
if (response.statusCode < 200 || response.statusCode > 299) {
reject(new Error('Failed to load page, status code: ' + response.statusCode));
}
// temporary data holder
const body = [];
// on every content chunk, push it to the data array
response.on('data', (chunk) => body.push(chunk));
// we are done, resolve promise with those joined chunks
response.on('end', () => resolve(body.join('')));
});
// handle connection errors of the request
request.on('error', (err) => reject(err))
})
};
let get = async function (url) {
var content = await getContent(url);
return content;
}
var html = get('https://developer.mozilla.org/it/');
In debug I receive this:
let get = async function (url) {
^^^^^^^^
SyntaxError: Unexpected token function
at Object.exports.runInThisContext (vm.js:78:16)
at Module._compile (module.js:543:28)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
Node 7.3.0 does not support async/await without a feature flag. Spawning node like this should do the trick:
node --harmony-async-await app.js
EDIT
Node now officially supports async/await by default in version 7.6.0, which comes from updating V8, Chromium’s JavaScript engine, to version 5.5.