简体   繁体   English

从node.js中的外部文件读取

[英]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). 我刚刚开始使用node.js,并且我一直在寻找方法来计算存储在机器上(与node.js应用程序不同的目录)中的cpp文件中的行数。

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')); 我现在尝试使用此功能从存储在node.js项目内的cpp文件中读取文本,该功能如下: console.log(fs.readFileSync('code.cpp', 'utf8'));

but I get this error: 但是我得到这个错误:

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

stringToFlags(flags), mode); 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. 错误:ENOENT:没有此类文件或目录,请在Object.fs.readFileSync(fs)上打开Object.fs.openSync(fs.js:646:18)上的'C:\\ Users \\ Heba \\ WebstormProjects \\ wrfile \\ sever.cpp' .js:551:33)。 (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) (C:\\ Users \\ Heba \\ WebstormProjects \\ wrfile \\ app.js:5:16)位于Object.Module._extensions..js(module.js:654:10)的Module._compile(module.js:643:30) )在Module.load(module.js:556:32)在tryModuleLoad(module.js:499:12)在Function.Module._load(module.js:491:3)在Module.require(module.js:587) :17)at require(internal / module.js:11:18)

Process finished with exit code 1 流程以退出代码1完成

Is this the right approach to the problem? 这是解决问题的正确方法吗? if so how can I fix this error? 如果可以,我该如何解决该错误?

Thanks in advance. 提前致谢。

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 确保'code.cpp'与脚本位于同一位置

try using path.join(__dirname, 'code.cpp'); 尝试使用path.join(__dirname, 'code.cpp');

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM