nodejs加载文件 [英] nodejs load file

查看:231
本文介绍了nodejs加载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用nodejs加载test.txt。

I want to load test.txt with nodejs.

var fs = require('fs');
fs.readFile('./test.txt', function (err, data) {
  if (err) {
    throw err; 
  }
  console.log(data);
});

服务器的路径是 C:\\\\\\\\\ \\server.js 。 test.txt位于同一目录中,但是我收到此错误:错误:ENOENT,没有这样的文件或目录'C:\ Users \ User \ test.txt'

The path of the server is C:\server\test\server.js. The test.txt is located in the same directory, but I get this error: Error: ENOENT, no such file or directory 'C:\Users\User\test.txt'

推荐答案

Node中的路径是相对于当前工作目录解析的。使用 __ dirname 为您的路径添加前缀,以解析Node脚本位置的路径。

Paths in Node are resolved relatively to the current working directory. Prefix your path with __dirname to resolve the path to the location of your Node script.

var fs = require('fs');
fs.readFile( __dirname + '/test.txt', function (err, data) {
  if (err) {
    throw err; 
  }
  console.log(data.toString());
});

这篇关于nodejs加载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆