Heba
Heba

Reputation: 37

Reading from an external file in node.js

I've just started using node.js, and I have been looking for ways to count the number of lines in a cpp file stored on my machine (in a different directory from that of the node.js app).

I am trying just read text from a cpp file stored inside the node.js project for now, with this function: console.log(fs.readFileSync('code.cpp', 'utf8'));

but I get this error:

fs.js:646 return binding.open(pathModule._makeLong(path),

stringToFlags(flags), mode); ^

Error: ENOENT: no such file or directory, open 'C:\Users\Heba\WebstormProjects\wrfile\sever.cpp' at Object.fs.openSync (fs.js:646:18) at Object.fs.readFileSync (fs.js:551:33) at Object. (C:\Users\Heba\WebstormProjects\wrfile\app.js:5:16) at Module._compile (module.js:643:30) at Object.Module._extensions..js (module.js:654:10) at Module.load (module.js:556:32) at tryModuleLoad (module.js:499:12) at Function.Module._load (module.js:491:3) at Module.require (module.js:587:17) at require (internal/module.js:11:18)

Process finished with exit code 1

Is this the right approach to the problem? if so how can I fix this error?

Thanks in advance.

Upvotes: 1

Views: 2990

Answers (1)

Abslen Char
Abslen Char

Reputation: 3135

according to the error that you get , your script cant locate the file. make sur that 'code.cpp' is in the same location as your script

try using path.join(__dirname, 'code.cpp');

var fs = require('fs'),
    path = require('path'),    
    file = path.join(__dirname, 'code.cpp');

console.log(fs.readFileSync(file, 'utf8'));

Upvotes: 2

Related Questions